467

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.

2
  • 8
    So, how do you check if the DOM is ready? Commented Dec 24, 2014 at 16:19
  • saw this working if java scripts are loading async stackoverflow.com/questions/8618464/… Commented Sep 29, 2020 at 2:08

15 Answers 15

672

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!")
})
Sign up to request clarification or add additional context in comments.

9 Comments

so, just to clarify (if I may), comparing to DOM ready, window.onload is called when every page component/resourse (i.e. *including *images). Am I right?
@BreakPhreak: yes :) onload waits for all resources that are part of the document. This excludes, of course, requests created dynamically that are not part of the document itself, e.g., an AJAX request.
script is not loaded fully
What if my script may be dynamically loaded and "load" event occurred before I added my handler?
Did anybody faced issue with this approach in IE ? I am facing issues with IE11
|
43

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

4 Comments

This answer is precisely opposite of what was asked in the question.
Indeed the DOMContentLoaded event is triggered when all DOM contents have been loaded, before it has loaded all its dependencies. Since users in the thread of answers referenced $.ready I thought it made a good contribution. Btw. I'd use the addEventListener-method also for the load event though, as it allows you to have multiple callbacks: window.addEventListener("load", function(event){ // your code here });
my DOMContentLoaded event is not fired
@Dee it should, it is quite an old event supported by all major browsers for years; perhaps you have some slow loading resources on your page. If you need help sorting out your particular problem, please ask a new question.
38

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

5 Comments

"interactive" is not fully loaded. "complete" is fully loaded
At last! Thanks a million, Jacob. All the numerous methods listed here having failed (at best, a radiobutton would be updated, and a resulting calculation could be done, but the button would not appear pressed), your method does the trick.
Not fully working. Maybe it works in most cases, but I have this SPA that triggers readyState complete even if content is still loading, which is most of it's elements. The only solution was to wait for it with a setTimeout. BTW, it's for a tampermonkey script, so I don't have full control over the SPA.
@JasonXA Seems to be the same deal for me, I'm trying to do similar working on a browser extension for SPA's like Twitch, Kick, etc. and this code seems to be hit or miss. Please post the code for your solution if you can.
It's a simple code: let tsc = setInterval(() => { if (runSet()) { clearInterval(tsc); }}, 1000); runSet will return true or false if it finds the element it's supposed to, on true, it will stop the interval.
34

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 MDN 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();">

1 Comment

Can anyone clarify how this trick works? Too complicated for me, doh..
24

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

3 Comments

$(window) makes me think this would be jquery -- right? Or am I getting some javascript syntax confused? (I'm new to JS).
why not simply use $(document).ready(); when jQuery is available?
yours is the document (more or less just the parsed HTML), the other ("load") is everything including images and styles. Depends on what you need.
10

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

Comments

9

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.

Comments

9

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.

Comments

8

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.

5 Comments

Ah brilliant. Well ive done this. The last image on the page is this: <img src="imdbupdate.php?update=ajax" style="display:hidden" onload="window.location = 'movies.php?do=admincp'" /> However it doesn't readirect me
...what? You want to redirect once an image loads?
I'm not sure why you'd want that, but the reason it doesn't redirect may be that it's display:hidden, and thus the browser doesn't bother to load it since it will not be shown.
maybe it's just a hidden image that does something important on the server, such as tracking a hit or doing something in the DB?
I can get that, but to have it redirect after doesn't make sense to me. Why have the page at all if you don't want the user to spend time on it? And if the goal is to redirect on load, why not just use a window.onload event, since it's a cleaner implementation overall?
7

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

Comments

4

This calls yourFunction() after the page has loaded, whether or not the document has already loaded by the time this code is executed

if (document.readyState === 'complete') yourFunction();
else window.addEventListener('load', () => yourFunction());

See https://javascript.info/onload-ondomcontentloaded for thorough teaching about stuff like this.

Comments

2

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

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

Comments

2

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

Comments

1

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

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

Comments

-5

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!");
});

1 Comment

This doesn't have anything related with the question. This code is related to an Ajax request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.