How to execute a function when page has fully loaded?

Javascript

Javascript Problem Overview


I need to execute some JavaScript code when the page has fully loaded. This includes things like images.

I know you can check if the DOM is ready, but I don’t know if this is the same as when the page is fully loaded.

Javascript Solutions


Solution 1 - Javascript

That's called load. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that load waited on images.

window.addEventListener('load', function () {
  alert("It's loaded!")
})

Solution 2 - Javascript

Usually you can use window.onload, but you may notice that recent browsers don't fire window.onload when you use the back/forward history buttons.

Some people suggest weird contortions to work around this problem, but really if you just make a window.onunload handler (even one that doesn't do anything), this caching behavior will be disabled in all browsers. The MDC documents this "feature" pretty well, but for some reason there are still people using setInterval and other weird hacks.

Some versions of Opera have a bug that can be worked around by adding the following somewhere in your page:

<script>history.navigationMode = 'compatible';</script>

If you're just trying to get a javascript function called once per-view (and not necessarily after the DOM is finished loading), you can do something like this:

<img src="javascript:location.href='javascript:yourFunction();';">

For example, I use this trick to preload a very large file into the cache on a loading screen:

<img src="bigfile"
onload="this.location.href='javascript:location.href=\'javascript:doredir();\';';doredir();">

Solution 3 - Javascript

For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported

document.addEventListener("DOMContentLoaded", function(event){
  // your code here
});

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

Solution 4 - Javascript

Try this it Only Run After Entire Page Has Loaded

By Javascript

window.onload = function(){
    // code goes here
};

By Jquery

$(window).bind("load", function() {
    // code goes here
});

Solution 5 - Javascript

Try this code

document.onreadystatechange = function () {
  if (document.readyState == "complete") {
    initApplication();
  }
}

visit https://developer.mozilla.org/en-US/docs/DOM/document.readyState for more details

Solution 6 - Javascript

the window.onload event will fire when everything is loaded, including images etc.

You would want to check the DOM ready status if you wanted your js code to execute as early as possible, but you still need to access DOM elements.

Solution 7 - Javascript

Javascript using the onLoad() event, will wait for the page to be loaded before executing.

<body onload="somecode();" >

If you're using the jQuery framework's document ready function the code will load as soon as the DOM is loaded and before the page contents are loaded:

$(document).ready(function() {
    // jQuery code goes here
});

Solution 8 - Javascript

You may want to use window.onload, as the docs indicate that it's not fired until both the DOM is ready and ALL of the other assets in the page (images, etc.) are loaded.

Solution 9 - Javascript

In modern browsers with modern javascript (>= 2015) you can add type="module" to your script tag, and everything inside that script will execute after whole page loads. e.g:

<script type="module">
  alert("runs after") // Whole page loads before this line execute
</script>
<script>
  alert("runs before")
</script>

also older browsers will understand nomodule attribute. Something like this:

<script nomodule>
  alert("tuns after")
</script>

For more information you can visit javascript.info.

Solution 10 - Javascript

And here's a way to do it with PrototypeJS:

Event.observe(window, 'load', function(event) {
    // Do stuff
});

Solution 11 - Javascript

> The onload property of the GlobalEventHandlers mixin is an event > handler for the load event of a Window, XMLHttpRequest, element, > etc., which fires when the resource has loaded.

So basically javascript already has onload method on window which get executed which page fully loaded including images...

You can do something:

var spinner = true;

window.onload = function() {
  //whatever you like to do now, for example hide the spinner in this case
  spinner = false;
};

Solution 12 - Javascript

If you need to use many onload use $(window).load instead (jQuery):

$(window).load(function() {
    //code
});

Solution 13 - Javascript

Completing the answers from @Matchu and @abSiddique.

This:

window.addEventListener('load', (event) => {
  console.log('page is fully loaded');
});

Is the same as this but using the onload event handler property:

window.onload = (event) => {
  console.log('page is fully loaded');
};

Source:

https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

Live example here:

https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#live_example

Solution 14 - Javascript

2019 update: This is was the answer that worked for me. As I needed multiple ajax requests to fire and return data first to count the list items.

$(document).ajaxComplete(function(){
       alert("Everything is ready now!");
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen ShelockView Question on Stackoverflow
Solution 1 - JavascriptMatchuView Answer on Stackoverflow
Solution 2 - JavascriptgeocarView Answer on Stackoverflow
Solution 3 - JavascriptmurbView Answer on Stackoverflow
Solution 4 - JavascriptabSiddiqueView Answer on Stackoverflow
Solution 5 - JavascriptJacob NelsonView Answer on Stackoverflow
Solution 6 - JavascriptcodeflyView Answer on Stackoverflow
Solution 7 - JavascriptDefonceskoView Answer on Stackoverflow
Solution 8 - JavascriptMarc NovakowskiView Answer on Stackoverflow
Solution 9 - JavascriptPouria MoosaviView Answer on Stackoverflow
Solution 10 - JavascriptMark BiekView Answer on Stackoverflow
Solution 11 - JavascriptAlirezaView Answer on Stackoverflow
Solution 12 - JavascriptSebastien HorinView Answer on Stackoverflow
Solution 13 - JavascriptOgglasView Answer on Stackoverflow
Solution 14 - Javascriptnorcal johnnyView Answer on Stackoverflow