JavaScript tips:window.onload與$(document).ready()的差異

來源:互聯網
上載者:User

標籤:ntc   res   協議   event   turn   var   loaded   任務   return   

1、window.onload在$(document).ready()之後執行

原因:二者觸發與否,都是依據document.readyState這個屬性。

(1)document.readyState的值:uninitialized、loading、interactive、complete(這四個值,依據時間先後排序)。

(2)當其值為interactive時,會觸發documentContentLoaded事件,JQuery.ready()就是對documentContentLoaded事件設計了一個函數,從而執行JQuery.ready定義的任務隊列。

(3)當其值為complete時,會觸發load事件。

(4)綜上,window.onload會在$(document).ready()之後執行。

協議原文:document . readyState

Returns "loading" while the Document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.

The readystatechange event fires on the Document object when this value changes.

 

2、window.onload多次賦值會產生覆蓋現象,而$(document).ready()不會。

原因:

(1)onload是window對象的成員方法,是指向堆記憶體中的Function類型的Object的引用。因為JavaScript不存在函數重載機制,所以對onload多次賦值,會導致解除上一次對某Function的引用,轉而將引用指向當前函數的引用,從而產生覆蓋現象。

(2)$(document).ready()實現了一個任務對象,多次傳入function,向任務隊列中添加一個成員而已。

JavaScript tips:window.onload與$(document).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.