$(document).ready(function() {
// do stuff when DOM is ready
});
當瀏覽器處理好DOM時則會執行function中的程式,那如何做到?答案是,JavaScript告訴Browser使用事件偵聽函式的方式。在jQuery程式碼中,有一段程式碼,就是它:
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( .addEventListener ) {
// Use the handy event callback
.addEventListener( "DOMContentLoaded", function(){
.removeEventListener( "DOMContentLoaded", arguments.callee, false );
jQuery.ready();
}, false );
// If IE event model is used
} else if ( .attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
.attachEvent("onreadystatechange", function(){
if ( .readyState === "complete" ) {
.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
// If IE and not an iframe
// continually check to see if the is ready
if ( .Element.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/
.Element.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 );
}
沒有留言:
張貼留言