Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between onload and script at end of body?

I'm new to JS and I'm not sure when exactly the functions are executed.

Example A:

 <html>
  <head>
    <title>A</title>
    <script src="myScript.js"></script>
  </head>
  <body onload="myFunction()">
    [Content here...]
  </body>
</html>

Example B:

<html>
  <head>
    <title>B</title>
    <script src="myScript.js"></script>
  </head>
  <body>
    [Content here...]
    <script>
      myFunction();
    </script>
  </body>
</html>

From what I've read so far the function is executed when the parser reaches it. Wouldn't that make example A and B the same? Is all the content (e.g. a table with text) of the page visible on the screen when myFunction() is called in B?

like image 875
John Avatar asked Oct 07 '15 17:10

John


2 Answers

Adding the <script> at the end of the body essentially runs it once the items before that <script> are processed (you can think of it like running when the DOM of the body is done). Although onload waits not only for the DOM, but for all the contents inside to be completely done loading, such as images.

like image 67
Spencer Wieczorek Avatar answered Sep 30 '22 17:09

Spencer Wieczorek


onLoad will wait untill the whole document has finished loading with images and such. The good thing about putting your scripts before the closing body tag, is that the user would see the page rendered sooner, if you have a heavy script in your head that takes a couple of seconds to download, the user would see a blank page until it loads the scripts and continues downloading the rest of the document. I would use both, onLoad to make sure the scripts gets executed when everything has loaded, and scripts at bottom so that users has the feeling that the page is loading fast :)

like image 25
taxicala Avatar answered Sep 30 '22 16:09

taxicala