Javascript load script on page load

How to make JavaScript execute after page load?

I’m executing an external script, using a

For cases where «right after page load» is still too early: Run JavaScript after all window.onload scripts have completed?.

25 Answers 25

These solutions will work:

As mentioned in comments use defer:

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

document.onload didn’t work for me. I found this post w/ the same issue stackoverflow.com/questions/5135638/…. Doesn’t seem like document.onload is an option.

ALL of these options are much later than necessary, given the goal of running javascript once DOM is ready to be manipulated. Two better choices for that goal: 1) Use defer attribute on javascript link in head. 2) move any javascript that accesses DOM to bottom of page, immediately before .

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»

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.

* 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()< // . >); 

Event Listeners with readyStates — Alternative solution (readystatechange):

// 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; >>); 

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/

And if all of the above points are still to early.

What if you need your script to run after other scripts are run, including those scheduled to run at the very end (e.g. those scheduled for the «load» event)? See Run JavaScript after all window.onload scripts have completed?

What if you need to make sure your script runs after some other script, regardless of when it is run? This answer to the above question has that covered too.

@Peter pretty sure this stands alone probably best if it in the bottom of your javascript files so it executes last

Re asynchronous javascript: to clarify, there are two choices for scripts that don’t immediately run. Of those, defer is usually preferable to async — because defer won’t interrupt html parsing/rendering — and when it runs, DOM is guaranteed to be ready. Efficiently load JavaScript with defer and async.

+1 I tried window.onload = . thinking that my script would wait until everything was fully downloaded before running but it seems window.onload actually behaves like document.addEventListener(«DOMContentLoaded», . , whereas the window.addEventListener(«load», . really does wait for everything to be fully downloaded. I would have thought that window.onload should be equivalent to window.addEventListener(«load», . rather than document.addEventListener(«DOMContentLoaded», . ?? I got the same result in Chrome and FF.

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

+1 for posting almost exactly what I had to come up with 6 months ago. Code like this can be necessary if other frameworks and code that you have no control over are adding onload events and you want to as well without wiping out the other onload events. I included my implementation as a function and it required var newonload = function(evt) < curronload(evt); newOnload(evt); >because for some reason the framework I am using requires an event to be passed to the onload event.

I just discovered in testing that the code as written results in handlers being fired in an undefined order when attached with attachEvent(). If order-of-handler-execution is important you may want to leave out the window.attachEvent branch.

So this will add this Function as an ADDITIONAL function to run OnLoad, correct? (rather than replacing an existing onload event)

You can put a «onload» attribute inside the body

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.

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

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.

This is wrong fundamentally. Defer does not prevent execution post page onload. Both defer and async scripts are loaded before page load, instead, improves the «domInteraction» time.

@Akansh the OP just wanted a way to ensure the DOM had loaded before their script executes. Defer does this, it’s literally written in the documentation snippet I shared in my answer.

It looks like you can make inline script load after page load using async false? «To achieve a similar effect for dynamically inserted scripts use async=false instead. — 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.»

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

  

Where do I place this?

Paste code in your HTML just before the 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

I think this solution, combined with the answer of chaos user (stackoverflow.com/a/807997/10712525), will be the best thing that u can do.

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

Is onload called before or after all resources (such as fonts and images) are loaded and properly visually updated?

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

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()< setTimeout( function()< doSomethingCool(); >, 1000); >; 
  
    function myFunction() 

Hello World!

document.onreadystatechange = function() < if(document.readyState === 'complete')< /*code here*/ >> 

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

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

Comparison

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

Оцените статью