177

I am using following code to execute some statements after page load.

 <script type="text/javascript">
    window.onload = function () { 

        newInvite();
        document.ag.src="b.jpg";
    }
</script>

But this code does not work properly. The function is called even if some images or elements are loading. What I want is to call the function the the page is loaded completely.

10
  • 1
    Could you add a demo on JSFiddle.net?
    – Some Guy
    Commented Aug 13, 2012 at 14:53
  • 2
    Could you use jQuery? If so, try $(window).load() Commented Aug 13, 2012 at 14:55
  • 1
    Yes, could you explain exactly what isn't working properly? Are you getting an error, or perhaps you're calling an alert function before the window redraws (making it look like it's called before load)? The code looks fine, and forcing users to download large libraries probably won't fix this issue or make it any easier to diagnose. Commented Aug 13, 2012 at 15:06
  • 1
    How do you determine that the image isn't loaded? I usually test by checking to see if the image's width is greater than 0. Commented Aug 13, 2012 at 15:46
  • 1
    Does this answer your question? How to make JavaScript execute after page load?
    – T.Todua
    Commented Feb 9, 2021 at 21:08

16 Answers 16

216

this may work for you :

document.addEventListener('DOMContentLoaded', function() {
   // your code here
}, false);

or if your comfort with jquery,

$(document).ready(function(){
// your code
});

$(document).ready() fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).

as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout function, before firing the function like below :

setTimeout(function(){
 //your code here
}, 3000);
11
  • 17
    jQuery's ready will not do what the OP requested. ready fires when the DOM loads, not after elements load. load will fire after the elements finish loading/rendering. Commented Aug 13, 2012 at 15:02
  • 1
    It looks like the OP wants all the elements to be loaded entirely, not just the HTML. Commented Aug 13, 2012 at 15:03
  • 3
    @shreedhar or he could use the right tool for the job (load). Commented Aug 13, 2012 at 15:42
  • 23
    setTimeout is a bad idea. It relies on the page loading under 3 seconds (or n seconds depending on what value you choose.) If loading takes longer, it won't work, and if the page loads faster, it'll have to wait for no reason.
    – JJJ
    Commented Jul 4, 2016 at 12:09
  • 2
    @ChristianMatthew its useCapture If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTargets beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation.
    – Shreedhar
    Commented Aug 31, 2016 at 11:31
100

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 = ...
5
  • 2
    is this cross browser supported Commented Feb 21, 2019 at 0:04
  • 1
    Yes, it is caniuse.com/mdn-api_document_readystate Commented Jun 4, 2021 at 9:01
  • Either just delete your answer or delete the other dupe, but don’t vandalise it by turning it into a link. Commented Aug 17, 2021 at 23:36
  • event.target.readyState === "complete" is really useful, thank you! I think this should be the right answer, not the highest ranking one. Commented Aug 23, 2022 at 11:04
  • much better solution than the top answer
    – Bigbob23
    Commented Aug 18, 2023 at 1:12
50

I'm little bit confuse that what you means by page load completed, "DOM Load" or "Content Load" as well? In a html page load can fire event after two type event.

  1. DOM load: Which ensure the entire DOM tree loaded start to end. But not ensure load the reference content. Suppose you added images by the img tags, so this event ensure that all the img loaded but no the images properly loaded or not. To get this event you should write following way:

    document.addEventListener('DOMContentLoaded', function() {
       // your code here
    }, false);
    

    Or using jQuery:

    $(document).ready(function(){
    // your code
    });
    
  2. After DOM and Content Load: Which indicate the the DOM and Content load as well. It will ensure not only img tag it will ensure also all images or other relative content loaded. To get this event you should write following way:

    window.addEventListener('load', function() {...})
    

    Or using jQuery:

    $(window).on('load', function() {
     console.log('All assets are loaded')
    })
    
4
  • 4
    This is the only answer here that gives a non-jQuery solution for the OP, with a clear explanation
    – Velojet
    Commented Jan 21, 2018 at 4:14
  • @Hanif DOMContentLoaded event handler doesn't seem to do anything for me but load does. Commented Jan 31, 2018 at 20:09
  • 1
    Don't the last two examples need semicolons at the end of the lines?
    – R. Navega
    Commented Feb 25, 2018 at 1:04
  • #2 is what I needed, ran perfectly.
    – Nhan
    Commented Sep 8, 2021 at 19:42
37

If you can use jQuery, look at load. You could then set your function to run after your element finishes loading.

For example, consider a page with a simple image:

<img src="book.png" alt="Book" id="book" />

The event handler can be bound to the image:

$('#book').load(function() {
  // Handler for .load() called.
});

If you need all elements on the current window to load, you can use

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

If you cannot use jQuery, the plain Javascript code is essentially the same amount of (if not less) code:

window.onload = function() {
  // run code
};
6
  • 2
    Doesn't the jQuery load method just bind a function to the load event using Javascript? How would this be any different than what the OP is already doing? Commented Aug 13, 2012 at 14:58
  • @AlexKalicki AFAIK it wouldn't be any different, except that jQuery might use addEventListener rather than bind the DOM0 onload property.
    – Alnitak
    Commented Aug 13, 2012 at 14:59
  • @AlexKalicki I cannot say that it uses the exact same functionality, but according to the documentation, jQuery is ensuring that all elements including images are loaded before this fires. I would tend to believe that there would be additional logic in place if this is the case, and I have no reason to disbelieve the documentation, although I have never run into the same issue the OP is reporting. Commented Aug 13, 2012 at 15:01
  • 4
    As of JQuery v1.8, .load is deprecated. source Commented Mar 12, 2013 at 20:12
  • 1
    Best solution ever for the question. Commented May 10, 2017 at 23:49
14

You're best bet as far as I know is to use

window.addEventListener('load', function() {
    console.log('All assets loaded')
});

The #1 answer of using the DOMContentLoaded event is a step backwards since the DOM will load before all assets load.

Other answers recommend setTimeout which I would strongly oppose since it is completely subjective to the client's device performance and network connection speed. If someone is on a slow network and/or has a slow cpu, a page could take several to dozens of seconds to load, thus you could not predict how much time setTimeout will need.

As for readystatechange, it fires whenever readyState changes which according to MDN will still be before the load event.

Complete

The state indicates that the load event is about to fire.

1
  • good but about the last paragraph: The readystatechange = 'Complete' is ok to assume whole page and contents (images, scripts, css) are all loaded. Although it is before load event but it doesn't matter here Commented Jan 7, 2022 at 7:55
11

If you wanna call a js function in your html page use onload event. The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.

<body onload="callFunction();">
....
</body>
1
  • Tried, didn't work. Using document.addEventListener('DOMContentLoaded', function() { // your code here }, false); works.
    – John T
    Commented Nov 6, 2020 at 0:55
7

This way you can handle the both cases - if the page is already loaded or not:

document.onreadystatechange = function(){
    if (document.readyState === "complete") {
       myFunction();
    }
    else {
       window.onload = function () {
          myFunction();
       };
    };
}
1
  • While this is shown in the MDN docs, it doesn’t work if more than one script uses document.onreadystatechange—only the last one loaded will execute, all others be ignored. It’s much better to attach an event listener—that works even when many attach to the same event. Sorry, wanted to attach sample but can’t make this thing format code… document.addEventListener('readystatechange', event => { if (event.target.readyState === "complete") {
    – Moonbase
    Commented Dec 5, 2023 at 21:18
7

you can try like this without using jquery

window.addEventListener("load", afterLoaded,false);
function afterLoaded(){
alert("after load")
}

5
window.onload = () => {
  // run in onload
  setTimeout(() => {
    // onload finished.
    // and execute some code here like stat performance.
  }, 10)
}
3
  • 3
    While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – yivi
    Commented Dec 26, 2017 at 9:18
  • 1
    @yivi if that's not an automated message: it's pretty obvious to anyone what that code means, especially since there are comments in the code.. Commented Feb 21, 2019 at 0:05
  • this works best to me. even if you remove the setTimeout block or just keep it there ;-)
    – Jeo
    Commented May 25, 2023 at 12:16
4

Alternatively you can try below.

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

This works in all the case. This will trigger only when the entire page is loaded.

1

I tend to use the following pattern to check for the document to complete loading. The function returns a Promise (if you need to support IE, include the polyfill) that resolves once the document completes loading. It uses setInterval underneath because a similar implementation with setTimeout could result in a very deep stack.

function getDocReadyPromise()
{
  function promiseDocReady(resolve)
  {
    function checkDocReady()
    {
      if (document.readyState === "complete")
      {
        clearInterval(intervalDocReady);
        resolve();
      }
    }
    var intervalDocReady = setInterval(checkDocReady, 10);
  }
  return new Promise(promiseDocReady);
}

Of course, if you don't have to support IE:

const getDocReadyPromise = () =>
{
  const promiseDocReady = (resolve) =>
  {
    const checkDocReady = () =>
      ((document.readyState === "complete") && (clearInterval(intervalDocReady) || resolve()));
    let intervalDocReady = setInterval(checkDocReady, 10);
  }
  return new Promise(promiseDocReady);
}

With that function, you can do the following:

getDocReadyPromise().then(whatIveBeenWaitingToDo);
0

I can tell you that the best answer I found is to put a "driver" script just after the </body> command. It is the easiest and, probably, more universal than some of the solutions, above.

The plan: On my page is a table. I write the page with the table out to the browser, then sort it with JS. The user can resort it by clicking column headers.

After the table is ended a </tbody> command, and the body is ended, I use the following line to invoke the sorting JS to sort the table by column 3. I got the sorting script off of the web so it is not reproduced here. For at least the next year, you can see this in operation, including the JS, at static29.ILikeTheInternet.com. Click "here" at the bottom of the page. That will bring up another page with the table and scripts. You can see it put up the data then quickly sort it. I need to speed it up a little but the basics are there now.

</tbody></body><script type='text/javascript'>sortNum(3);</script></html>

MakerMikey

-1

If you're already using jQuery, you could try this:

$(window).bind("load", function() {
   // code here
});
1
  • 5
    Useless without explanation.
    – Daniel W.
    Commented Nov 7, 2016 at 16:58
-2

call a function after complete page load set time out

setTimeout(function() {
   var val = $('.GridStyle tr:nth-child(2) td:nth-child(4)').text();
	for(var i, j = 0; i = ddl2.options[j]; j++) {
		if(i.text == val) {      
			ddl2.selectedIndex = i.index;
			break;
		}
	} 
}, 1000);

0
-4

Try this jQuery:

$(function() {
 // Handler for .ready() called.
});
1
  • 1
    jQuery's ready will not do what the OP requested. ready fires when the DOM loads, not after elements load. load will fire after the elements finish loading/rendering. Commented Aug 13, 2012 at 15:03
-6

Put your script after the completion of body tag...it works...

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.