Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has window.onload event already fired

I have a small javascript util which may get preloaded, lazy loaded or loaded on demand. When it's initiated it adds some stuff to the DOM. It's low priority and if it's preloaded it can wait for the onload event to fire before running, but if it's lazy loaded it can go ahead and run immediately.

Currently It's checking to see if the ID of the footer element exists to determine if it should add an event listener to the window onload event or just run. e.g.

if ( document.getElementById("footer") ){
   Init()
} else {
   if (window.addEventListener){...}
   else if (window.attachEvent){...}
}

Although currently working, this is obviously a pretty poor solution. Any non jQuery related suggestions on improving this gratefully received!

like image 549
Patrick Clancey Avatar asked Mar 22 '13 12:03

Patrick Clancey


People also ask

Is window onload deprecated?

Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.

Is window onload an event?

JavaScript has a window onload event to launch certain functions whenever a web page is loaded. The onload event is also used for verification of type and version of visitor's browser. Further cookies can also be checked through the onload attribute. The attribute of onload triggers when the object is loaded in HTML.

Does document onload and window onload fire at the same time?

document. onload event is fired before the window. onload.


1 Answers

You should use document.readyState property:

if (document.readyState === 'complete') {
   //do stuff
}
like image 52
Artyom Neustroev Avatar answered Oct 06 '22 02:10

Artyom Neustroev