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?
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With