6

So I know that if you use jQuery you can use $(document).load(function(){}); so that any code you write into the function gets executed after the whole page has loaded, but is there a way of doing something similar if you don't use jQuery and just use JS?

For example...

<html>
    <head>
        <script type="text/javascript">
            var box = document.getElementById('box');
            alert(box);
        </script>
    </head>
    <body>
        <div id="box" style="width:200px; height:200px; background-color:#999; 
margin:20px;"></div>
    </body>
</html>  

If I use this method the alert just says null. So is there a way of making the js code run once the page has loaded?

Jerry
  • 67,172
  • 12
  • 92
  • 128
user1563944
  • 303
  • 4
  • 17
  • Actually, when using jQuery, please **do not** use `$(document).load(function(){...});` – adeneo May 25 '13 at 20:09
  • This question might have an answer that you need [http://stackoverflow.com/questions/799981...](http://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery) – Tafadzwa Gonera May 25 '13 at 20:14

4 Answers4

14

I use:

<script type="text/javascript">
    window.onload = function(){
        //do stuff here
    };
</script>

This way you don't have to use any onload tags in your html.

Nile
  • 1,556
  • 1
  • 14
  • 25
8

The easiest way is to simply put your script at the end of the document, typically just before the closing body tag:

<html>
<head>

</head>
<body>
<div id="box" style="width:200px; height:200px; background-color:#999; margin:20px;"></div>
<script type="text/javascript">
    var box = document.getElementById('box');
    alert(box);
</script>
</body>

</html>
79IT
  • 425
  • 4
  • 9
  • so get the js to find the element #box the js tags have to go within the body section rather than within the head tag? – user1563944 May 25 '13 at 20:14
  • @user1563944 - more specifically, the javascript has to come after the element you're trying to access, otherwise the element does'nt exist when the javascript executes. – adeneo May 25 '13 at 20:14
4

You can use a variety of methods to accomplish this.

The simplest, easiest method would be to simply add the script tag at the end of your body tag:

<html>
<head>
    <title> Example </title>
</head>
<body>
    <div>
        <p>Hello</p>
    </div>
    <script type="text/javascript">
        // Do stuff here
    </script>
</body>
</html>

The way jQuery does it is something similar to:

window.onload = function() {
    // Do stuff here
}

I usually just do it the second way, just in case.

To ensure cross-browser compatibility, crawl through the source of jQuery and find what they use.

Anish Gupta
  • 2,150
  • 2
  • 21
  • 37
2

You can use onload in your body tag.

<head>
   <script type="text/javascript">
      function doSomething() {
         //your code here
      }
   </script>
</head>
<body onload="doSomething()">
Robbert
  • 6,286
  • 5
  • 30
  • 58