我有一个使用的脚本$(document).ready,但没有使用jQuery中的其他任何脚本。我想通过删除jQuery依赖项来减轻它的负担。
$(document).ready
如何在$(document).ready不使用jQuery的情况下实现自己的功能?我知道使用window.onload会有所不同,因为window.onload在加载所有图像,帧等之后会触发。
window.onload
有一个基于标准的替代品,尽管IE8不DOMContentLoaded支持,但超过98%的浏览器都支持它:
DOMContentLoaded
document.addEventListener("DOMContentLoaded", function(event) { //do work });
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 ); }