頁面初始化中,用的較多的就是$(document).ready(function(){//代碼}); 或 $(window).load(function(){//代碼});javascript
他們的區別就是,ready是在DOM的結構加載完後就觸發,load是在頁面內包括DOM結構,css,js,圖片等都加載完成後再觸發,顯然ready更適合做爲頁面初始化使用。但有時候也不盡然。須要進一步查看其內部機制。css
那麼ready的內部是如何判斷DOM的結構加載完的?而且不一樣的瀏覽器的判斷是如何的?java
答案就在jquery代碼內,假設jquery的版本是jquery-1.11.3.js。jquery
ready的關鍵代碼(3507~3566行),關鍵代碼用紅色標出:promise
jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); };
上面的代碼在觸發ready時能夠分紅兩部分瀏覽器
1.標準瀏覽器下的觸發 dom
當瀏覽器是基於標準瀏覽器時,會在加載完DOM結構後觸發「DOMContentLoaded」事件,jquery內部就用此事件做爲ready的觸發源。async
document.addEventListener( "DOMContentLoaded", completed, false );
2.IE瀏覽器下的觸發spa
當瀏覽器是IE瀏覽器時,由於IE瀏覽器(蛋疼並強大着)不支持「DOMContentLoaded」事件,因此只能另謀它法,code
(function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })();
IE下的作法 就是上面代碼的紅字處,用「document.documentElement.doScroll("left")」的方法去滾動頁面,若是沒加載完就等個50毫秒後繼續滾,直到滾的動後就觸發ready。
可是,若是頁面中有frame的場合,會使用window.onload事件做爲ready的觸發源。
因此在IE下,頁面中有frame時,ready也是等到頁面內的全部內容加載完成後再觸發。