jquery事件的ready()方法使用詳解,jqueryready

來源:互聯網
上載者:User

jquery事件的ready()方法使用詳解,jqueryready

頁面初始化中,用的較多的就是$(document).ready(function(){//代碼}); 或 $(window).load(function(){//代碼});

他們的區別就是,ready是在DOM的結構載入完後就觸發,load是在頁面內包括DOM結構,css,js,圖片等都載入完成後再觸發,顯然ready更適合作為頁面初始化使用。但有時候也不盡然。需要進一步查看其內部機制。

那麼ready的內部是如何判斷DOM的結構載入完的?並且不同的瀏覽器的判斷是如何的?

答案就在jquery代碼內,假設jquery的版本是jquery-1.11.3.js。

ready的關鍵代碼(3507~3566行),關鍵代碼用紅色標出:

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結構後觸發“DOMContentLoaded”事件,jquery內部就用此事件作為ready的觸發源。

document.addEventListener( "DOMContentLoaded", completed, false );

2.IE瀏覽器下的觸發

當瀏覽器是IE瀏覽器時,因為IE瀏覽器(蛋疼並強大著)不支援“DOMContentLoaded”事件,所以只能另謀它法,

        (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也是等到頁面內的所有內容載入完成後再觸發。

jQuery中ready與load事件的區別

大家在工作中用jQuery的時候一定會在使用之前這樣:

//document ready$(document).ready(function(){  ...code...})//document ready 簡寫$(function(){  ...code...})

有些時候也會這麼寫:

//document load$(document).load(function(){  ...code...})

一個是ready一個是load,這兩個到底有什麼區別呢?今天我們來聊一聊。
ready與load誰先執行:

大家在面試的過程中,經常會被問到一個問題:ready與load那一個先執行,那一個後執行?答案是ready先執行,load後執行。
DOM文檔載入的步驟:

要想理解為什麼ready先執行,load後執行就要先聊一下DOM文檔載入的步驟:

(1) 解析HTML結構。(2) 載入外部指令碼和樣式表檔案。(3) 解析並執行指令碼代碼。(4) 構造HTML DOM模型。//ready(5) 載入圖片等外部檔案。(6) 頁面載入完畢。//load

從上面的描述中大家應該已經理解了吧,ready在第(4)步完成之後就執行了。但是load要在第(6)步完成之後才執行。

ready事件:

ready事件在DOM結構繪製完成之後就繪執行。這樣能確保就算有大量的媒體檔案沒載入出來,JS代碼一樣可以執行。

load事件:

load事件必須等到網頁中所有內容全部載入完畢之後才被執行。如果一個網頁中有大量的圖片的話,則就會出現這種情況:網頁文檔已經呈現出來,但由於網頁資料還沒有完全載入完畢,導致load事件不能夠即時被觸發。

總結:

相信大家已經瞭解了ready與load的區別,其實如果頁面中要是沒有圖片之類的媒體檔案的話ready與load是差不多的,但是頁面中有檔案就不一樣了,所以還是推薦大家在工作中用ready。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.