428

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.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Ben Shelock
  • 20,154
  • 26
  • 92
  • 125

15 Answers15

631

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!")
})
Matchu
  • 83,922
  • 18
  • 153
  • 160
  • 4
    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 Jun 22 '11 at 09:21
  • 23
    @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. – Matchu Jun 22 '11 at 18:49
  • 6
    script is not loaded fully – HD.. Oct 23 '15 at 10:28
  • 1
    What if my script may be dynamically loaded and "load" event occurred before I added my handler? – ptkoz Aug 30 '16 at 10:40
  • Did anybody faced issue with this approach in IE ? I am facing issues with IE11 – Deepak Yadav Dec 28 '16 at 12:30
  • @Matchu - thanks for this amazing answer, how include the AJAX request in the scope of the observer ? – HoCo_ Aug 23 '18 at 12:56
  • Doesn't work. At least on I-phone/IOS (as of IOS 12, both chrome and safari), putting this in the initial page in a stand alone – Randy Sep 04 '20 at 00:21
  • @Randy Maybe it's the bug [geocar mentions below?](https://stackoverflow.com/a/1033557/4751990) – Egor Hans Sep 10 '21 at 06:28
  • Is there a way to take advantage of the await async syntax? Using multiple nested callbacks would be ugly... – Umberto Fontanazza Oct 23 '22 at 22:07
40

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

murb
  • 1,736
  • 21
  • 31
  • 16
    This answer is precisely opposite of what was asked in the question. – Muhammad bin Yusrat Dec 25 '17 at 19:25
  • 2
    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 });` – murb Jan 02 '18 at 18:08
  • my DOMContentLoaded event is not fired – Dee Jul 10 '22 at 12:48
  • 1
    @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. – murb Jul 12 '22 at 11:12
35

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();">
Community
  • 1
  • 1
geocar
  • 9,085
  • 1
  • 29
  • 37
27

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

TheTechGuy
  • 16,560
  • 16
  • 115
  • 136
Jacob Nelson
  • 2,370
  • 23
  • 35
  • Yeah, this is helpful. Thanks a lot~ – Bravo Yeung Mar 05 '19 at 15:55
  • 6
    `"interactive"` is not fully loaded. `"complete"` is fully loaded – Ryan Walker Nov 07 '19 at 21:22
  • 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. – secr Jun 13 '20 at 20:11
25

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
});
abSiddique
  • 11,647
  • 3
  • 23
  • 30
  • 1
    `$(window)` makes me think this would be jquery -- right? Or am I getting some javascript syntax confused? (I'm new to JS). – Azendale Nov 11 '15 at 20:51
  • 2
    why not simply use `$(document).ready();` when jQuery is available? – Andreas Jun 03 '16 at 15:22
  • 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. – amenthes Oct 25 '16 at 20:19
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
});
Defoncesko
  • 657
  • 5
  • 25
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.

codefly
  • 640
  • 1
  • 5
  • 8
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.

Marc Novakowski
  • 44,628
  • 11
  • 58
  • 63
  • Ah brilliant. Well ive done this. The last image on the page is this: However it doesn't readirect me – Ben Shelock Jun 23 '09 at 16:02
  • ...what? You want to redirect once an image loads? – Matchu Jun 23 '09 at 16:06
  • 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. – Matchu Jun 23 '09 at 16:07
  • 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? – Marc Novakowski Jun 23 '09 at 16:53
  • 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? – Matchu Jun 23 '09 at 18:04
6

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.

Brad
  • 159,648
  • 54
  • 349
  • 530
Pouria Moosavi
  • 662
  • 7
  • 22
2

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

Event.observe(window, 'load', function(event) {
    // Do stuff
});
Mark Biek
  • 146,731
  • 54
  • 156
  • 201
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;
};
Alireza
  • 100,211
  • 27
  • 269
  • 172
2

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

Ogglas
  • 62,132
  • 37
  • 328
  • 418
1

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

$(window).load(function() {
    //code
});
Sebastien Horin
  • 10,803
  • 4
  • 52
  • 54
0

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.

davidbludlow
  • 1,873
  • 1
  • 16
  • 9
-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!");
});
Ömürcan Cengiz
  • 2,085
  • 3
  • 22
  • 28
norcal johnny
  • 2,050
  • 2
  • 13
  • 17
  • 1
    This doesn't have anything related with the question. This code is related to an Ajax request. – Jackal Sep 07 '20 at 14:43