ready事件是當DOM檔案樹加載完成后執行一個函式(不包含圖片,css等),因此它的觸發要早于load事件,用法:
- $(document).ready(fun) ;fun是一個函式,這樣當DOM樹加載完畢后就會執行該匿名函式了
ready有一個簡寫,可以直接傳入$(fun)即可,這是因為在jQuey內部也定義了一個$(document)的jQuery物件,和我們在上面的寫法是一樣的
ready事件和window的onload區別:
- ready事件 ;等dom樹載完畢后就可以執行
- onload事件 ;等網頁中所有的資源加載完畢后(包括圖片,flash,音頻,視頻)才能執行
onload事件還可以系結在某個圖片上面,舉個例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> </head> <body> <img src="https://www.cnblogs.com/images/logo_small.gif" alt=""> <script> $(()=>console.log('DOM樹已加載完畢')) //ready事件 $('img').on('load',()=>console.log('圖片已加載完畢')) //圖片的加載事件 $(window).on('load',()=>console.log('資源已加載完畢')) //網頁所有資源都加載完畢后的事件 </script> </body> </html>
這里我們用了箭頭函式來寫,代碼很簡單了,我們在系結了一個ready事件,一個圖片上的onload事件和window上的onload事件,加載后輸出如下:

可以看到首先是ready事件的觸發,然后是圖片的onload事件,最后是window的onload事件的觸發,此時所有資源都已經加載完了
原始碼分析
jquery的ready事件就是在document上系結了一個DOMContentLoaded事件物件,對他進行了一下封裝,DOMContentLoaded事件的原理可以看看看這篇文章,介紹得挺詳細的:https://www.cnblogs.com/caizhenbo/p/6679478.html
jQuery的ready事件是基于函式串列實作的,函式串列可以看這個連接:https://www.cnblogs.com/greatdesert/p/11433365.html
當我們呼叫$(fun)去執行一個ready事件的時候首先會執行入口模塊里的邏輯,與ready相關的如下:
init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { /*略*/ } else if ( jQuery.isFunction( selector ) ) { //如果引數selector是函式,則認為是系結ready事件 return rootjQuery.ready( selector ); //則執行rootjQuery.ready()方法,并把selector作為引數傳入 } /*略*/ },
rootjQuery是jQuery內部定義的一個區域變數,是一個jQuery實體,如下:
rootjQuery = jQuery(document); //第917行,保存了document物件參考的jQuery實體
在入口模塊參考rootjQuery.ready()也就是執行了rootjQuery實體物件上的ready方法(該方法是定義在原型上的),如下:
jQuery.fn = jQuery.prototype = { ready: function( fn ) { // Attach the listeners jQuery.bindReady(); //先執行jQuery.bindReady()系結ready事件(實際上系結的是DOMContentLoaded或onreadystatechange事件) // Add the callback readyList.add( fn ); //為函式串列readyList增加一個函式 return this; } }
jQuery.bindReady()是一個靜態方法,用于系結事件的,內部會初始化readyList為一個jQuery.Callbacks( "once memory" )函式串列物件
然后執行readyList.add( fn )將fn函式保存到函式串列readyList里面,
jQuery.bindReady()的實作如下:
jQuery.extend({ bindReady: function() { //初始化ready事件監聽函式串列readyList,并為document物件系結ready事件主監聽函式DOMContentLoaded if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); //呼叫jQuery.Callbacks(flags)ready事件監聽函式串列readylist,同時傳入once和memory標記, // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { //如果檔案已經就緒,則呼叫jQuery.ready(wait)執行ready事件監聽函式串列readyList // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); //通過setTimeout()異步執行方法jQuery.ready(wait),以允許其他腳本延遲ready事件的觸發, } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { //在IE9+及以上瀏覽器系結DOMContentLoaded事件 // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); //把監聽函式DOMContentLoaded系結到document物件的DOMContentLoaded事件上 // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onl oad, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, /*略*/ })
這里我們呼叫document.addEventListener在document上系結了一個DOMContentLoaded事件,這樣當DOM樹加載完后就會執行DOMContentLoaded函式了,DOMContentLoaded函式的定義如下:
if ( document.addEventListener ) { //如果是IE9+和其他瀏覽器 DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); //先移除document的DOMContentLoaded事件 jQuery.ready(); //再呼叫jQuery.ready()執行ready事件監聽函式 }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; }
函式內首先會移除DOMContentLoaded事件,然后呼叫jQuery.ready()事件,這是DOM樹觸發后的事件了(我們在jQuery.fn.ready()內執行了readyList.add( fn )增加的函式都會依次觸發),如下:
jQuery.extend({ isReady: false, ready: function( wait ) { //實際執行的函式 觸發ready事件監聽函式串列readyList和資料快取物件中的ready事件監聽函式, // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { //如果wait是true且jQuery.readyWait等于0 或者 wait不是true且jQuery.isReady是false 則執行 初始化jQuery.isReady為false的 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; //設定jQuery.inReady為true,表示ready事件已就緒, // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.fireWith( document, [ jQuery ] ); //執行ready事件監聽函式readyList,背景關系是document(即關鍵詞this),[jQuery]是ready事件監聽函式的引數, // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, /*略*/ })
writer by:大沙漠 QQ:22969969
最后呼叫readyList.fireWith()方法去觸發回掉函式串列里的每個函式,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/34143.html
標籤:jQuery
