jQuery 如何? domReady 和 onload 判斷

來源:互聯網
上載者:User

jQuery 如何? domReady 和 onload 判斷

對於 jQuery 使用中 $( function(){} ) 的形式我們都不陌生,將事件函數綁定在 dom 載入完畢的時刻,相對於 window.onload 來講可以避免一些圖片,動態指令碼,以及一些外部資源等載入對於當前代碼執行帶來的較大的延時影響,因為 window.onload 是需要等當前頁面需要載入的資源全部載入結束後才觸發執行,包括 onload 觸發之前執行的動態載入。

對於標準瀏覽器,具有 DOMContentLoaded 事件來作為 dom 載入完畢後觸發的事件,當然準確點說的話是 dom 和 非動態載入的JS 載入完畢時刻觸發(關於觸發時機可以看這裡 JS、CSS以及img對DOMContentLoaded 事件的影響)。

當然低版本的IE(IE6 ~ IE8)不支援 DOMContentLoaded 事件,那麼也需要使用一些其他的方法來進行類比 DOMContentLoaded 時刻觸發。當前主流的低版本IE類比方法就是使用 doScroll 進行迴圈判斷,對於 JScript ,若在 dom 未載入完畢時刻調用 doScroll 則會報錯,藉此使用 try catch 進行輪詢判定。

那麼,要瞭解 jQuery 對 domReady 和 load 的區分,其實就是說 jQuery 對於兼用的 domReady 是如何?的而已,因為 onload 是各個瀏覽器已經實現的事件,而 DOMContentLoaded 未被低版本IE實現。然後本次使用的 jQuery 版本為 1.11,畢竟還要包括以下低版本IE,所以不使用 2.*的版本,但其實質是一樣的,只不過 2.*版本中就捨棄使用 doScroll 進行迴圈判定放棄低版本IE而已。那麼,要瞭解本質,最好的辦法還是看 jQuery 源碼。

  1. // DOM ready 的 一個 jQuery deferred
  2. // 也作為 綁定初始化的判定標籤
  3. var readyList;

  4. // 調用綁定才進行 綁定初始化
  5. jQuery.fn.ready = function( fn ) {
  6. // 未初始化過的才進行初始化綁定
  7. jQuery.ready.promise().done( fn );
  8. return this;
  9. };

  10. jQuery.extend({
  11. // DOM ready 是否觸發過標籤
  12. isReady: false,
  13. readyWait: 1,

  14. holdReady: function( hold ) {
  15. if ( hold ) {
  16. jQuery.readyWait++;
  17. } else {
  18. jQuery.ready( true );
  19. }
  20. },

  21. // DOM ready 時刻的事件控制代碼
  22. ready: function( wait ) {

  23. if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
  24. return;
  25. }

  26. // IE的小BUG 確保 body 已經存在
  27. if ( !document.body ) {
  28. return setTimeout( jQuery.ready );
  29. }

  30. // 切換標籤狀態
  31. jQuery.isReady = true;

  32. // 是否需要等待的標籤
  33. if ( wait !== true && --jQuery.readyWait > 0 ) {
  34. return;
  35. }

  36. // 執行以 jquery 形式的 ready 綁定
  37. readyList.resolveWith( document, [ jQuery ] );

  38. // 在次觸發其他形式的綁定,並且及時登出
  39. if ( jQuery.fn.triggerHandler ) {
  40. jQuery( document ).triggerHandler( "ready" );
  41. jQuery( document ).off( "ready" );
  42. }
  43. }
  44. });

擴充的 isReady 是用來控制 ready 的執行次數的,readyWait 和 holdReady 在此不在此文解釋範圍,其中的 ready 方法 就是核心了,為 jQuery 判定 domReady 時所觸發的方法,又結合了 defferred 的 resolveWith 逐一執行儲存在 cache 中事件控制代碼數組中的事件控制代碼。那麼接下來就是 domReady 的重頭戲,判定 domReady 時刻。

  1. // 移除所有有關事件控制代碼 compeleted 的綁定事件
  2. function detach() {
  3. if ( document.addEventListener ) {
  4. document.removeEventListener( "DOMContentLoaded", completed, false );
  5. window.removeEventListener( "load", completed, false );
  6. } else {
  7. document.detachEvent( "onreadystatechange", completed );
  8. window.detachEvent( "onload", completed );
  9. }
  10. }

  11. // 對於已經過了 domReady 時間點
  12. function completed() {
  13. // 標準瀏覽器 或者 為 IE下的load事件 或者 ready 狀態為 complete(IE)
  14. if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
  15. detach();
  16. jQuery.ready();
  17. }
  18. }

  19. jQuery.ready.promise = function( obj ) {
  20. if ( !readyList ) {
  21. // 初始化 readyList
  22. readyList = jQuery.Deferred();

  23. // 當 $(document).ready() 早在 ready 事件過後被調用的時候,直接觸發。
  24. if ( document.readyState === "complete" ) {
  25. // 非同步方式執行 類似的類比事件觸發形式
  26. setTimeout( jQuery.ready );

  27. // DOMContentLoaded 事件綁定
  28. } else if ( document.addEventListener ) {
  29. document.addEventListener( "DOMContentLoaded", completed, false );
  30. window.addEventListener( "load", completed, false );

  31. // 這邊則是低版本IE形式
  32. } else {
  33. document.attachEvent( "onreadystatechange", completed );
  34. window.attachEvent( "onload", completed );

  35. // IE的 doScroll 方式檢測
  36. var top = false;

  37. try {
  38. top = window.frameElement == null && document.documentElement;
  39. } catch(e) {}

  40. if ( top && top.doScroll ) {
  41. (function doScrollCheck() {
  42. if ( !jQuery.isReady ) {
  43. try {
  44. top.doScroll("left");
  45. } catch(e) {
  46. // 當try中有錯誤 直接下次延遲迴圈檢測
  47. return setTimeout( doScrollCheck, 50 );
  48. }

  49. detach();
  50. jQuery.ready();
  51. }
  52. })();
  53. }
  54. }
  55. }
  56. return readyList.promise( obj );
  57. };

其實對於 jQuery 這種形式來說,有點類似於 寧可錯殺一千,也不放過一個,在任何狀態下儘可能的多監聽些事件進行判斷,在 DOMContentLoaded,load,readystatechange 以及 doScroll 迴圈等, 反正有 jQuery.isReady 進行把關麼,怕什麼。對於該流程進一步瞭解還需要去瞭解一下 jquery 的 promise。關於 jQuery 的 callback, defferred的作用和源碼。為什麼要返回 readyList.promise( obj ),自己思考下吧!






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.