JavaScript Window onload to execute script as soon as page loads and difference between body onload

preview_player
Показать описание
Script execution as soon as page load and difference between window onload and using onload function in body tag

The other way to achieve the same result is by using onload inside body tag of the page. You can read this article on how to keep the onload event handler to set the focus on input tag once the page loads. �

Document onload is executed when DOM is ready ( Not necessarily all connected script, images etc to be downloaded )

#windowOnload #bodyOnload
Рекомендации по теме
Комментарии
Автор

You made a big mistake that invalidates you claim about window.onload. window.onload always fires after body.onload. Mistake you made is that you immediately executed my_code function by adding brackets. window.onload = my_code is a correct way, not window.onload = my_code(). I your case, you are assigning RESULT of the function, not function itself. Brackets are needed only when you integrate handler into html tag (inline handler), which is the worst way to add event handler.

Either
window.onload = my_code;
document.body.onload = my_code;

addEventListener('load', my_code); // Preferred way
document.body.addEventListener('load', my_code);

or
<body onload="my_code()">

Brackets are only in last example.

iponik
visit shbcf.ru