execute function after complete page load

JavascriptHtmlImage

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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 = ...

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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>

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

you can try like this without using jquery

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

Solution 9 - Javascript

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.

Solution 10 - Javascript

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

Solution 11 - Javascript

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

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Solution 15 - Javascript

Try this jQuery:

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

Solution 16 - Javascript

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

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
QuestionNeeraj KumarView Question on Stackoverflow
Solution 1 - JavascriptShreedharView Answer on Stackoverflow
Solution 2 - JavascriptT.ToduaView Answer on Stackoverflow
Solution 3 - JavascriptHanifView Answer on Stackoverflow
Solution 4 - JavascriptJaime TorresView Answer on Stackoverflow
Solution 5 - Javascriptuser2361682View Answer on Stackoverflow
Solution 6 - JavascriptRyan WalkerView Answer on Stackoverflow
Solution 7 - Javascripttsveti_ikoView Answer on Stackoverflow
Solution 8 - JavascriptNAAView Answer on Stackoverflow
Solution 9 - JavascriptGanesh Ram RaviView Answer on Stackoverflow
Solution 10 - JavascripttvrcgoView Answer on Stackoverflow
Solution 11 - JavascriptsantoshView Answer on Stackoverflow
Solution 12 - JavascriptMicheal MorrowView Answer on Stackoverflow
Solution 13 - JavascriptPaul RoweView Answer on Stackoverflow
Solution 14 - JavascriptM.HView Answer on Stackoverflow
Solution 15 - JavascriptdjservaView Answer on Stackoverflow
Solution 16 - JavascriptBossView Answer on Stackoverflow