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.
load(function(){ // ...}) @undefined, this is almost the same as $(document). ready(function(){ ... }) . load() will wait until the graphics are also loaded.
jQuery $(document). ready() Equivalent in JavaScriptThis event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ). on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. // A $( document ).
There is a standards based replacement,DOMContentLoaded
that is supported by over 99% 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 ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With