Cross browser home is ready

I inherited this piece of code, and it seems suboptimal and possibly wrong, as it adds event listeners to both the window and the document objects. However, it works correctly, with the exception of Blackberry 5.0. Can someone explain if this is all set up correctly or are there any recommendations to make it better and / or more streamlined?

if (document.readyState === "complete") callback(); else if (document.addEventListener) { document.addEventListener("DOMContentLoaded",callback,false); window.addEventListener("load",callback,false); } else if(window.attachEvent) { document.attachEvent("onreadystatechange", callback); window.attachEvent("onLoad",callback); } else setTimeout(callback,2000); 
+20
javascript javascript-events onload-event
Aug 01 2018-11-11T00:
source share
3 answers

If you want to know how to do it or see how to do it. I recommend watching the work of Diego Perini. Its work and methods are used in many DOM libraries, including jQuery. Unfortunately, the guy doesn't seem to deserve much attention. It was he who became the pioneer of the try / catch polling method, which makes it possible to use events loaded in the browser when IE throws itself into the mix.

https://github.com/dperini/ContentLoaded/blob/master/src/contentloaded.js

+63
Aug 01 2018-11-18T00:
source share

If you want to use pure javascript, you can use the following cross-browser function (source (in Russian): http://javascript.ru/unsorted/top-10-functions )

 function bindReady(handler){ var called = false function ready() { if (called) return called = true handler() } if ( document.addEventListener ) { document.addEventListener( "DOMContentLoaded", function(){ ready() }, false ) } else if ( document.attachEvent ) { if ( document.documentElement.doScroll && window == window.top ) { function tryScroll(){ if (called) return if (!document.body) return try { document.documentElement.doScroll("left") ready() } catch(e) { setTimeout(tryScroll, 0) } } tryScroll() } document.attachEvent("onreadystatechange", function(){ if ( document.readyState === "complete" ) { ready() } }) } if (window.addEventListener) window.addEventListener('load', ready, false) else if (window.attachEvent) window.attachEvent('onload', ready) /* else // use this 'else' statement for very old browsers :) window.onload=ready */ } readyList = [] function onReady(handler) { if (!readyList.length) { bindReady(function() { for(var i=0; i<readyList.length; i++) { readyList[i]() } }) } readyList.push(handler) } 

Using:

 onReady(function() { // ... }) 
+5
Aug 01 '11 at 18:01
source share

Personally, I would use jQuery for this.

jQuery is designed to handle a variety of browser uses when the document is ready.

Using jQuery, your code will look like this:

 $(callback); 
+3
Aug 01 '11 at 17:48
source share



All Articles