JavaScript tips:window.onload与$(document).ready()的差异

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,向任务队列中添加一个成员而已。

原文地址:https://www.cnblogs.com/niconicohang/p/6511518.html