Reputation: 83
Given that my js script file in put in the bottom of a page, is "window.onload" in:
var elem1;
window.onload = () => {
elem1 = document.getElementById("element1");
};
really needed? As opposed to simply:
var elem1 = document.getElementById("element1");
If there's no difference, will this still remain true if I add "async" to it? Namely:
<script async src="...."></script>
Upvotes: 1
Views: 1190
Reputation: 2018
window.onload
is used when you want to execute JavaScript after the HTML is done the parsing. It makes sure all the HTML tags are rendered.
Async
in script tag is used when you want to execute the JavaScript when the browser is parsing the HTML ( script get executed when available as soon as possible ).
About your question, if there is no difference:
There is a difference between loading the script vs loading a script with async.
The script tag will block the render if you don't use async.
Upvotes: 1
Reputation: 1054
No. The page is loaded from top to bottom in terms of code. If you have your script at the bottom of the page, it will be loaded last, so therefore you don't need window.onload because the page has already been loaded.
Upvotes: 3