Wednesday, 2 August 2017

javascript - $(document).ready equivalent without jQuery




I have a script that uses $(document).ready, but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency.



How can I implement my own $(document).ready functionality without using jQuery? I know that using window.onload will not be the same, as window.onload fires after all images, frames, etc. have been loaded.


Answer



There is a standards based replacement,DOMContentLoaded that is supported by over 98% of browsers, though not IE8:



document.addEventListener("DOMContentLoaded", function(event) { 
//do work
});



jQuery's native function is much more complicated than just window.onload, as depicted below.



function bindReady(){
if ( readyBound ) return;
readyBound = true;

// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {

// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
jQuery.ready();
}, false );

// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes

document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});

// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){

if ( jQuery.isReady ) return;

try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}


// and execute any waiting functions
jQuery.ready();
})();
}

// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...