$(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.
我目前有一個JS檔正在用$(document).ready,但是我目前想要拿掉jQuery
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.
在此情況下我該如何應用才能不使用jQuery達到同樣的功能呢?我知道window.onload一定不一樣
There is a standards based replacement,DOMContentLoaded that is supported by over 98% of browsers, though not IE8:
有一個標準的用法DOMContentLoaded,98%的瀏覽器都支援,除了IE8:
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
jQuery's native function is much more complicated than just window.onload, as depicted below.
jQuery的原生函式比window.onload複雜非常多,如下所述:
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 );
}