jquery ready函数深入分析
最近看一些关于jqueryready有人说他缓慢,有人说他快,说法不一。于是自己深入研究一下。首先看了一下jquery文档关于ready的描述
WhileJavaScriptprovidestheloadeventforexecutingcodewhenapageisrendered,thiseventdoesnotgettriggereduntilallassetssuchasimageshavebeencompletelyreceived.Inmostcases,thescriptcanberunassoonastheDOMhierarchyhasbeenfullyconstructed.Thehandlerpassedto.ready()isguaranteedtobeexecutedaftertheDOMisready,sothisisusuallythebestplacetoattachallothereventhandlersandrunotherjQuerycode.WhenusingscriptsthatrelyonthevalueofCSSstyleproperties,it'simportanttoreferenceexternalstylesheetsorembedstyleelementsbeforereferencingthescripts. Incaseswherecodereliesonloadedassets(forexample,ifthedimensionsofanimagearerequired),thecodeshouldbeplacedinahandlerfortheloadeventinstead.
翻译一下
虽然JavaScript提供了load事件,当页面渲染完成之后会执行这个函数,在所以元素加载完成之前,这个函数不会被调用,例如图像。但是在大多数情况下,只要DOM结构加载完,脚本就可以尽快运行。传递给.ready()的事件句柄在DOM准备好后立即执行,因此通常情况下,最好把绑定事件句柄和其他jQuery代码都到这里来。但是当脚本依赖于CSS样式属性时,一定要在脚本之前引入外部样式或内嵌样式的元素。
如果代码依赖于需加载完的元素(例如,想获取一个图片的尺寸大小),应该用.load()事件代替,并把代码放到load事件句柄中。
依照文档上面的说明,在页面内有大量文档结构,图片资源时候,ready是快于load的。文档里面也清晰的分析了什么时候用ready什么时候用load。
下面分析一下jqueryready的运行流程
$(handler)or$(document).ready(handler)→ ready()→bindReady()→执行readyList.add(fn)fn
大致看一下源码
下面是jquery的对象的ready源码
jQuery.fn=jQuery.prototype={ constructor:jQuery, init:function(selector,context,rootjQuery){ //HANDLE:$(function) //Shortcutfordocumentready //如果函数,则认为是DOMready句柄 if(jQuery.isFunction(selector)){ returnrootjQuery.ready(selector); } }, ready:function(fn){ //Attachthelisteners jQuery.bindReady();//绑定DOMready监听器,跨浏览器,兼容标准浏览器和IE浏览器 //Addthecallback readyList.add(fn);//将ready句柄添加到ready异步句柄队列 returnthis; } };
调用jquery的bindReady, 增加ready回调!
下面看一下bindReady大致源码
bindReady:function(){//jQuery.bindReady if(readyList){ return; } readyList=jQuery.Callbacks("oncememory")//初始化ready异步事件句柄队列 //Catchcaseswhere$(document).ready()iscalledafterthe //browsereventhasalreadyoccurred. //如果DOM已经完毕,立即调用jQuery.ready if(document.readyState==="complete"){ //Handleitasynchronouslytoallowscriptstheopportunitytodelayready //重要的是异步 returnsetTimeout(jQuery.ready,1); } //下面是一些防御性的编程故此省略 ...... }
这个应该很清楚 document.readyState=='complete'就会执行jquery的ready,我很困惑的是为什么是setTiemout(jQuery.ready,1),请返回上面看ready的代码,readyList.add(fn),如果不是异步的,执行回调的就会放到readyList.add(fn)之前了,因为执行是在jQuery的ready里面readyList.fireWith(document,[jQuery]);readylist是jquery的callbacks,就是管理回调函数的!不清楚的可以看看文档。
注:你会发现有两个ready,这两个是不同的,一个放到jquery.prototype就是我们$(doucument).ready这个,另一个是jquery的对象方法判断是否已经ready了的方法
ps:jquery博大精深,文章有错误之处,还请各位指正!
以上就是对jqueryready的资料整理,后续继续整理相关资料,谢谢大家对本站的支持!