javascript - Difference between onload and script at end of body? - Stack Overflow

admin2025-04-20  0

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?

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?

Share Improve this question asked Oct 7, 2015 at 17:17 JohnJohn 9854 gold badges14 silver badges30 bronze badges 1
  • onload will trigger once entire webpage including images,audio/video are loaded whereas before end of the body tag is like DOMContentLoaded event.. – Rayon Commented Oct 7, 2015 at 17:20
Add a ment  | 

2 Answers 2

Reset to default 5

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 pletely done loading, such as images.

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 :)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745114485a285781.html

最新回复(0)