Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 284
Robin Rodricks Avatar asked Apr 30 '09 16:04

Robin Rodricks


People also ask

How do I run JavaScript as soon as page loads?

If you are using an <script> inside <head> then use the onload attribute inside the <body> tag to Execute JavaScript after page load. It will run the function as soon as the webpage has been loaded.

Does JavaScript execute automatically?

Many JavaScript-enhanced web pages have scripts that must be executed automatically when the page is loaded. A web page containing a "scrolling status bar message," for example, should be able to start scrolling the message immediately after the page has loaded, without user interaction.

Which event do you use to run something after the page has finished loading?

The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded.


3 Answers

These solutions will work:

As mentioned in comments use defer:

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

or

<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.

like image 117
marcgg Avatar answered Oct 12 '22 15:10

marcgg


Triggering scripts in the right moment

A quick overview on how to load / run the script at the moment in which they intend to be loaded / executed.

Using "defer"

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

Using defer will trigger after domInteractive (document.readyState = "interactive") and just before "DOMContentLoaded" Event is triggered. If you need to execute the script after all resources (images, scripts) are loaded use "load" event or target one of the document.readyState states. Read further down for more information about those events / states, as well as async and defer attributes corresponding to script fetching and execution timing.

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.

Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.

Resource: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attributes

* See the images at the bottom for feather explanation.

Event Listeners - Keep in mind that loading of the page has more, than one event:

"DOMContentLoaded"

This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for style sheets, 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 images 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 style sheets

"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.

Executes after everything is loaded and parsed:

document.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

Event Listeners with readyStates - Alternative solution (readystatechange):

You can also track document.readystatechange states to trigger script execution.
// Place in header (do not use async or defer)
document.addEventListener('readystatechange', event => {
  switch (document.readyState) {
    case "loading":
      console.log("document.readyState: ", document.readyState,
       `- The document is still loading.`
       );
      break;
    case "interactive":
      console.log("document.readyState: ", document.readyState, 
        `- The document has finished loading DOM. `,
        `- "DOMContentLoaded" event`
        );
      break;
    case "complete":
      console.log("document.readyState: ", document.readyState, 
        `- The page DOM with Sub-resources are now fully loaded. `,
        `- "load" event`
        );
      break;
  }
});

MDN Resources: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState

Where to place your script (with & without async/defer)?

This is also very important to know where to place your script and how it positions in HTML as well as parameters like defer and async will affects script fetching, execution and HTML blocking.

* On the image below the yellow label “Ready” indicates the moment of ending loading HTML DOM. Then it fires: document.readyState = "interactive" >>> defered scripts >>> DOMContentLoaded event (it's sequential);

enter image description here

enter image description here

enter image description here

enter image description here

If your script uses async or defer read this: https://flaviocopes.com/javascript-async-defer/

like image 400
DevWL Avatar answered Oct 12 '22 15:10

DevWL


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;
    }
}
like image 208
chaos Avatar answered Oct 12 '22 15:10

chaos