Question

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.

No correct solution

OTHER TIPS

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

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

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

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>

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.

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

you can try like this without using jquery

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

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.

window.onload = () => {
  // run in onload
  setTimeout(() => {
    // onload finished.
    // and execute some code here like stat performance.
  }, 10)
}

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

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

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

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

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

Try this jQuery:

$(function() {
 // Handler for .ready() called.
});

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top