jquery源码 DOM加载
jQuery版本:2.0.3
DOM加載有關(guān)的擴展
- isReady:DOM是否加載完(內(nèi)部使用)?
- readyWait:等待多少文件的計數(shù)器(內(nèi)部使用)
- holdReady():推遲DOM觸發(fā)
- ready():準備DOM觸發(fā)。
- jQuery.ready.promise=function(){}; ?監(jiān)聽DOM的異步操作(內(nèi)部使用)
一、$(function(){})和原生window.onload的關(guān)系
這個在面試中也是經(jīng)常會被問到的。從下面幾個角度來分析一下它們的區(qū)別
1、執(zhí)行時機
頁面加載,先加載節(jié)點,再加載文件,比如img文件,flash等。
$(function(){})DOM加載完執(zhí)行??赡蹹OM元素關(guān)聯(lián)的東西并沒有加載完。
window.onload等節(jié)點和文件都加載完執(zhí)行。
對應的事件監(jiān)聽
jQuery用的是DOMContentLoaded事件。
DOMDContentLoaded:原生DOM加載事件,這個事件觸發(fā)代表DOM加載完了。
我之前寫過一篇文章的頁面加載時間分析里也有提到。
onload對應的是load事件。
2、個數(shù)
window.onload不能寫多個,后面的會覆蓋前面的。
$(function(){})可以寫多個。都會執(zhí)行 。
3、簡化寫法
$(function(){})是$(document)?.ready(function(){});的簡化寫法。
window.onload沒有簡化寫法。
二、jQurey如何實現(xiàn)DOM ready的
jQuery直接調(diào)用DOMContentLoaded來實現(xiàn)DOM的ready。但是DOMContentLoaded和onLoad一樣,瀏覽器只執(zhí)行一次,jQuery用什么判斷是否已經(jīng)執(zhí)行過呢?document.readyState就是判斷這個的依據(jù)。
readyState是document的屬性,總共有3個值:
- loading:文檔正在加載中
- interactive:文檔已經(jīng)加載完成,正在進行css和圖片等資源的加載
- complete:文檔的所以資源加載完成
判斷完之后如何回調(diào)呢?就是用Promise。jQuery通過new一個$.Deferred(promise)對象來實現(xiàn)對DOM的ready的回調(diào),在DOMContentLoaded中將這個promise給resolve掉,這樣就執(zhí)行了之前注冊的回調(diào)函數(shù),同時后面新注冊的回調(diào)也會立刻執(zhí)行。
但是在調(diào)用promise之前,jQuery執(zhí)行了一次setTimeout,因為jQuery.Promise是不會產(chǎn)生異步的,這和標準的promise規(guī)范是不一樣的,所有jQuery自己又手動做了一次setTimeout來實現(xiàn)異步。這樣使得無論使用在DOM的ready之前注冊的回調(diào)還是之后注冊的回調(diào)都會在異步中執(zhí)行。
三、源碼整體實現(xiàn)邏輯
$(fn)==>new一個 jQuery.fn.init(fn)==>返回$(document).ready( fn)。也就是說
- $(function(){}) =》
- 調(diào)用$(document).ready(function(){})=》
- 相當于$().ready(fn)實例方法=》
- 調(diào)用的jQuery.ready.promise().done(fn)=》
- jQuery.ready.promise中不管if還是else最終都是調(diào)用jQuery.ready(),并返回promise=》
- jQuery.ready()里面重點是readyList.resolveWith( document, [ jQuery ] );已完成。至此DOM加載完畢就可以調(diào)用fn了。
?
?
?
四、實現(xiàn)細節(jié)
1、重點是:jQuery.ready.promise()方法【巧妙】
如果DOM已經(jīng)加載完成了,調(diào)用jQuery.ready()這個工具方法;
如果DOM沒加載完,監(jiān)聽DOMContentLoaded事件和load事件,等事件發(fā)生時回調(diào)completed(),最終也是調(diào)用jQuery.ready()這個工具方法;
var // A central reference to the root jQuery(document) rootjQuery,// The deferred used on DOM ready readyList;jQuery.ready.promise = function( obj ) {if ( !readyList ) { //第一次readyList為空可以進來,后續(xù)就進不來if了,只執(zhí)行一次 readyList = jQuery.Deferred(); //第一步,創(chuàng)建延遲對象if ( document.readyState === "complete" ) { //DOM加載完成的標志就是document.readyState為complete,如果DOM已經(jīng)加載好了就直接調(diào)工具方法jQuery.ready。setTimeout( jQuery.ready );//加定時器是為了兼容IE} else {//DOM沒有加載完檢測,即檢測了DOMContentLoaded事件,也檢測了load事件;最終走回調(diào)completed函數(shù)// Use the handy event callbackdocument.addEventListener( "DOMContentLoaded", completed, false );// A fallback to window.onload, that will always workwindow.addEventListener( "load", completed, false ); //因為火狐瀏覽器會緩存load事件,為了第一時間相應所以對load也監(jiān)聽了 }}return readyList.promise( obj ); };completed回調(diào)函數(shù)如下,最終調(diào)用的也是jQuery.ready()。?
// The ready event handler and self cleanup methodcompleted = function() {//不管是DOMContentLoaded事件還是load發(fā)生,都會取消2個事件監(jiān)聽//jQuery.ready()只會觸發(fā)一次document.removeEventListener( "DOMContentLoaded", completed, false );window.removeEventListener( "load", completed, false );jQuery.ready();};2、jQuery.ready()工具方法做了些什么?
先做個測試:
$(function(arg){alert(this); //[object HTMLDocument]alert(arg); //jQuery函數(shù)})再做個測試:
除了$(function(){});$(document).ready(function(){}),也可以把ready當做事件來處理如下。
<script> $(document).on("ready",function(){alert(123); //123 }); </script>之所以會自動彈出123,是因為在jQuery源碼中用這句話jQuery( document ).trigger("ready").off("ready");來主動觸發(fā)了ready事件,觸發(fā)后再取消掉。
// Handle when the DOM is ready ready: function( wait ) { //參數(shù)和holdReady有關(guān)// Abort if there are pending holds or we're already readyif ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {return;}// Remember that the DOM is readyjQuery.isReady = true;// If a normal DOM Ready event fired, decrement, and wait if need beif ( wait !== true && --jQuery.readyWait > 0 ) {return;}//第一步看這里重點,resolveWith改變狀態(tài)的時候傳參了,給done中方法fn傳入了參數(shù),//document是fn的this指向,jQuery是參數(shù)// If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] );//跟主動觸發(fā)有關(guān)// Trigger any bound ready eventsif ( jQuery.fn.trigger ) {jQuery( document ).trigger("ready").off("ready");} },跟ready的參數(shù)有關(guān)的有一個holdReady()。
先做個測試
$.holdReady(true); $(function () {alert(123); //調(diào)用了holdReady并傳參true,就不能彈出123了 });可以推遲,也可以釋放推遲,釋放了以后就可以觸發(fā)了。
$.holdReady(true); $.holdReady(false); $(function () {alert(123); //釋放了holdReady,就彈出123 });這個有什么用?
比如:
$.getScript('js/a.js',function(){ //異步加載,不會影響后續(xù)代碼執(zhí)行。可能會產(chǎn)生一個問題,alert(2)先執(zhí)行了a.js還沒有加載完 })$(function () {alert(2);//先彈2,后彈出1 });很多時候引入外部文件的時候,都想等外部文件或者插件加載完,再去觸發(fā)操作,操作可能用到a.js。現(xiàn)在這個順序不對,會出問題。
怎樣解決這個問題?用holdReady()方法。
$.holdReady(true); //在這里先hold住$.getScript('js/a.js', function () { //異步加載,不會影響后續(xù)代碼執(zhí)行??赡軙a(chǎn)生一個問題,alert(2)先執(zhí)行了a.js還沒有加載完$.holdReady(false); //加載完釋放,不hold了就可以彈2了 })$(function () {alert(2);//先彈2,后彈出1});再深入一點,holdReady() 要針對的文件可能不止一個,有很多個,所以要等所有的文件都加載完再執(zhí)行,所以源碼中有一個計數(shù)的readyWait。
源碼中定義了一個等待棧變量——readyWait,每次執(zhí)行$.holdReady(true)都會增加壓棧,而每次$.holdReady()執(zhí)行都會彈棧,等空棧的時候就執(zhí)行jQuery.ready函數(shù),即將promise給resolve掉。
// Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1,//第二步看這里 //holdReady推遲DOM的觸發(fā) // Hold (or release) the ready event holdReady: function( hold ) {if ( hold ) {jQuery.readyWait++;//hold為真,讓readyWait加加處理} else {jQuery.ready( true );} },// Handle when the DOM is ready ready: function( wait ) { //參數(shù)和holdReady有關(guān)// Abort if there are pending holds or we're already ready//readyWait為0時就不用hold了,執(zhí)行后面的操作if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return;}// Remember that the DOM is readyjQuery.isReady = true; //默認是false// If a normal DOM Ready event fired, decrement, and wait if need beif ( wait !== true && --jQuery.readyWait > 0 ) {return;}//第一步看這里重點,resolveWith改變狀態(tài)的時候傳參了,給done中方法fn傳入了參數(shù),//document是fn的this指向,jQuery是參數(shù)// If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] );//跟主動觸發(fā)有關(guān)// Trigger any bound ready eventsif ( jQuery.fn.trigger ) {jQuery( document ).trigger("ready").off("ready");} },?
剛開始看源碼,很多地方理解也不到位,解釋可能也不清楚。
?
參考:
http://www.cnblogs.com/aeexiaoqiang/p/6525702.html
?
本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內(nèi)容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉(zhuǎn)載注明出處:http://www.cnblogs.com/starof/p/6856572.html有問題歡迎與我討論,共同進步。
轉(zhuǎn)載于:https://www.cnblogs.com/starof/p/6856572.html
總結(jié)
以上是生活随笔為你收集整理的jquery源码 DOM加载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux下mount FreeBSD分
- 下一篇: CSDN 厦门大学线下编程比赛第一题:求