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

I'm executing an external script, using a <script> inside <head>.

Now since the script executes before the page has loaded, I can't access the <body>, among other things. I'd like to execute some JavaScript after the document has been "loaded" (HTML fully downloaded and in-RAM). Are there any events that I can hook onto when my script executes, that will get triggered on page load?

This question is related to javascript html dom dom-events pageload

The answer is


Look at hooking document.onload or in jQuery $(document).load(...).


Working Fiddle on <body onload="myFunction()">

<!DOCTYPE html>
<html>
 <head>
  <script type="text/javascript">
   function myFunction(){
    alert("Page is loaded");
   }
  </script>
 </head>

 <body onload="myFunction()">
  <h1>Hello World!</h1>
 </body>    
</html>

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(window).bind("load", function() { _x000D_
_x000D_
// your javascript event here_x000D_
_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_


If you are using jQuery,

$(function() {...});

is equivalent to

$(document).ready(function () { })

or another short hand:

$().ready(function () { })

See What event does JQuery $function() fire on? and https://api.jquery.com/ready/


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/DOMContentLoaded https://developer.mozilla.org/en-US/docs/Web/Events/load

MDN list of all events:

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


<body onload="myFunction()">

This code works well.

But window.onload method has various dependencies. So it may not work all the time.


document.onreadystatechange = function(){
     if(document.readyState === 'complete'){
         /*code here*/
     }
}

look here: http://msdn.microsoft.com/en-us/library/ie/ms536957(v=vs.85).aspx


If the scripts are loaded within the <head> of the document, then it's possible use the defer attribute in script tag.

Example:

<script src="demo_defer.js" defer></script>

From https://developer.mozilla.org:

defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

To achieve a similar effect for dynamically inserted scripts use async=false instead. Scripts with the defer attribute will execute in the order in which they appear in the document.


Use this code with jQuery library, this would work perfectly fine.

$(window).bind("load", function() { 

  // your javascript event

});

$(window).on("load", function(){ ... });

.ready() works best for me.

$(document).ready(function(){ ... });

.load() will work, but it won't wait till the page is loaded.

jQuery(window).load(function () { ... });

Doesn't work for me, breaks the next-to inline script. I am also using jQuery 3.2.1 along with some other jQuery forks.

To hide my websites loading overlay, I use the following:

<script>
$(window).on("load", function(){
$('.loading-page').delay(3000).fadeOut(250);
});
</script>

You can put a "onload" attribute inside the body

...<body onload="myFunction()">...

Or if you are using jQuery, you can do

$(document).ready(function(){ /*code here*/ }) 

or 

$(window).load(function(){ /*code here*/ })

I hope it answer your question.

Note that the $(window).load will execute after the document is rendered on your page.


Comparison

In below snippet I collect choosen methods and show their sequence. Remarks

  • the document.onload (X) is not supported by any modern browser (event is never fired)
  • if you use <body onload="bodyOnLoad()"> (F) and at the same time window.onload (E) then only first one will be executed (because it override second one)
  • event handler given in <body onload="..."> (F) is wrapped by additional onload function
  • document.onreadystatechange (D) not override document .addEventListener('readystatechange'...) (C) probably cecasue onXYZevent-like methods are independent than addEventListener queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers.
  • all scripts write their timestamp in console - but scripts which also have access to div write their timestamps also in body (click "Full Page" link after script execution to see it).
  • solutions readystatechange (C,D) are executed multiple times by browser but for different document states:
    • loading - the document is loading (no fired in snippet)
    • interactive - the document is parsed, fired before DOMContentLoaded
    • complete - the document and resources are loaded, fired before body/window onload

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    // solution A_x000D_
    console.log(`[timestamp: ${Date.now()}] A: Head script`);_x000D_
    _x000D_
    // solution B_x000D_
    document.addEventListener("DOMContentLoaded", () => {_x000D_
      print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`);_x000D_
    });_x000D_
_x000D_
    // solution C_x000D_
    document.addEventListener('readystatechange', () => {_x000D_
      print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`);_x000D_
    });_x000D_
   _x000D_
    // solution D_x000D_
    document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)};_x000D_
    _x000D_
    // solution E (never executed)_x000D_
    window.onload = () => {_x000D_
      print(`E: <body onload="..."> override this handler`);_x000D_
    };_x000D_
_x000D_
    // solution F_x000D_
    function bodyOnLoad() {_x000D_
      print(`[timestamp: ${Date.now()}] F: <body onload='...'>`);      _x000D_
      infoAboutOnLoad(); // additional info_x000D_
    }_x000D_
    _x000D_
    // solution X_x000D_
    document.onload = () => {print(`document.onload is never fired`)};_x000D_
_x000D_
_x000D_
_x000D_
    // HELPERS_x000D_
_x000D_
    function print(txt) { _x000D_
      console.log(txt);_x000D_
      if(mydiv) mydiv.innerHTML += txt.replace('<','&lt;').replace('>','&gt;') + '<br>';_x000D_
    }_x000D_
    _x000D_
    function infoAboutOnLoad() {_x000D_
      console.log("window.onload (after  override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
      console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`);_x000D_
    }_x000D_
            _x000D_
    console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body onload="bodyOnLoad()">_x000D_
  <div id="mydiv"></div>_x000D_
_x000D_
  <!-- this script must te at the bottom of <body> -->_x000D_
  <script>_x000D_
    // solution G_x000D_
    print(`[timestamp: ${Date.now()}] G: <body> bottom script`);_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_


Using the YUI library (I love it):

YAHOO.util.Event.onDOMReady(function(){
    //your code
});

Portable and beautiful! However, if you don't use YUI for other stuff (see its doc) I would say that it's not worth to use it.

N.B. : to use this code you need to import 2 scripts

<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-min.js" ></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/event/event-min.js" ></script>

There is a very good documentation on How to detect if document has loaded using Javascript or Jquery.

Using the native Javascript this can be achieved

if (document.readyState === "complete") {
 init();
 }

This can also be done inside the interval

var interval = setInterval(function() {
    if(document.readyState === 'complete') {
        clearInterval(interval);
        init();
    }    
}, 100);

Eg By Mozilla

switch (document.readyState) {
  case "loading":
    // The document is still loading.
    break;
  case "interactive":
    // The document has finished loading. We can now access the DOM elements.
    var span = document.createElement("span");
    span.textContent = "A <span> element.";
    document.body.appendChild(span);
    break;
  case "complete":
    // The page is fully loaded.
    console.log("Page is loaded completely");
    break;
}

Using Jquery To check only if DOM is ready

// A $( document ).ready() block.
$( document ).ready(function() {
    console.log( "ready!" );
});

To check if all resources are loaded use window.load

 $( window ).load(function() {
        console.log( "window loaded" );
    });

In simple terms just use "defer" in the script tag.

.....

My advise use asnyc attribute for script tag thats help you to load the external scripts after page load

<script type="text/javascript" src="a.js" async></script>
<script type="text/javascript" src="b.js" async></script>

As Daniel says, you could use document.onload.

The various javascript frameworks hwoever (jQuery, Mootools, etc.) use a custom event 'domready', which I guess must be more effective. If you're developing with javascript, I'd highly recommend exploiting a framework, they massively increase your productivity.


Just define <body onload="aFunction()"> that will be called after the page has been loaded. Your code in the script is than enclosed by aFunction() { }.


<script type="text/javascript">
  function downloadJSAtOnload() {
   var element = document.createElement("script");
   element.src = "defer.js";
   document.body.appendChild(element);
  }
  if (window.addEventListener)
   window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
   window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>

http://www.feedthebot.com/pagespeed/defer-loading-javascript.html


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;
    }
}

I find sometimes on more complex pages that not all the elements have loaded by the time window.onload is fired. If that's the case, add setTimeout before your function to delay is a moment. It's not elegant but it's a simple hack that renders well.

window.onload = function(){ doSomethingCool(); };

becomes...

window.onload = function(){ setTimeout( function(){ doSomethingCool(); }, 1000); };

JavaScript

document.addEventListener('readystatechange', event => { 

    // When HTML/DOM elements are ready:
    if (event.target.readyState === "interactive") {   //does same as:  ..addEventListener("DOMContentLoaded"..
        alert("hi 1");
    }

    // When window loaded ( external resources are loaded too- `css`,`src`, etc...) 
    if (event.target.readyState === "complete") {
        alert("hi 2");
    }
});

same for jQuery:

$(document).ready(function() {   //same as: $(function() { 
     alert("hi 1");
});

$(window).load(function() {
     alert("hi 2");
});





NOTE: - Don't use the below markup ( because it overwrites other same-kind declarations ) :

document.onreadystatechange = ...

Here's a script based on deferred js loading after the page is loaded,

<script type="text/javascript">
  function downloadJSAtOnload() {
      var element = document.createElement("script");
      element.src = "deferredfunctions.js";
      document.body.appendChild(element);
  }

  if (window.addEventListener)
      window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
      window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>

Where do I place this?

Paste code in your HTML just before the </body> tag (near the bottom of your HTML file).

What does it do?

This code says wait for the entire document to load, then load the external file deferredfunctions.js.

Here's an example of the above code - Defer Rendering of JS

I wrote this based on defered loading of javascript pagespeed google concept and also sourced from this article Defer loading javascript


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to dom-events

Detecting real time window size changes in Angular 4 Does Enter key trigger a click event? What are passive event listeners? Stop mouse event propagation React onClick function fires on render How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over iFrame onload JavaScript event addEventListener, "change" and option selection Automatically pass $event with ng-click? JavaScript click event listener on class

Examples related to pageload

Auto-click button element on page load using jQuery Force page scroll position to top at page refresh in HTML How to make JavaScript execute after page load? $(document).ready equivalent without jQuery How to display a loading screen while site content loads Is there a cross-browser onload event when clicking the back button?