Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute function after complete page load [duplicate]

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.

like image 503
Neeraj Kumar Avatar asked Aug 13 '12 14:08

Neeraj Kumar


People also ask

How do I run a function after the page is loaded?

same for jQuery: $(document). ready(function() { //same as: $(function() { alert("hi 1"); }); $(window). load(function() { alert("hi 2"); });

What event do you use to perform something after the page has finished loading?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).


2 Answers

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); 
like image 63
Shreedhar Avatar answered Oct 06 '22 03:10

Shreedhar


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 = ... 
like image 33
T.Todua Avatar answered Oct 06 '22 04:10

T.Todua