How to make JavaScript execute after page load? How to make JavaScript execute after page load? javascript javascript

How to make JavaScript execute after page load?


These solutions will work:

<body onload="script();">

or

document.onload = function ...

or even

window.onload = function ...

Note that the last option is a better way to go since it is unobstrusive and is considered more standard.


Keep in mind that loading the page has more than one stage. Btw, this is pure JavaScript

"DOMContentLoaded"

This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. At this stage you could programmatically optimize loading of images and css based on user device or bandwidth speed.

Executes after DOM is loaded (before img and css):

document.addEventListener("DOMContentLoaded", function(){    //....});

Note: Synchronous JavaScript pauses parsing of the DOM. If you want the DOM to get parsed as fast as possible after the user requested the page, you could turn your JavaScript asynchronous and optimize loading of stylesheets

"load"

A very different event, load, should only be used to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

Exectues after everything is loaded and parsed:

window.addEventListener("load", function(){    // ....});

MDN Resources:

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoadedhttps://developer.mozilla.org/en-US/docs/Web/Events/load

MDN list of all events:

https://developer.mozilla.org/en-US/docs/Web/Events


Reasonably portable, non-framework way of having your script set a function to run at load time:

if(window.attachEvent) {    window.attachEvent('onload', yourFunctionName);} else {    if(window.onload) {        var curronload = window.onload;        var newonload = function(evt) {            curronload(evt);            yourFunctionName(evt);        };        window.onload = newonload;    } else {        window.onload = yourFunctionName;    }}