Home > Article > Web Front-end > In-depth analysis of how jQuery's ready function works (working principle)_jquery
This article provides an in-depth analysis of how jQuery’s ready function works. Share it with everyone for your reference, the details are as follows:
jQuery is a great scripting library, the first version was released by John Resig at BarCamp NYC in January 2006. You can download the latest version at http://jquery.com/. As of the publication of this article, it has been updated to jQuery version 2.1.4. Here we take jQuery1.8.3 as an example.
There are many ways to learn jQuery. Today we start with jQuery’s ready function. The code in this example comes from the jQuery script library.
If you have used jQuery, you must have used the ready function, which is used to register functions that can be executed when the page is ready.
The question is, when will our page be ready?
1. onload event
The most basic processing method is the onload event of the page. When we handle this event, there are many ways, that is, we can write it directly in the start tag of the body element through HTML, or we can use event registration. method to use, which can be divided into DOM0 method and DOM2 method. Taking into account browser compatibility, write it in DOM2 mode, as shown below.
if (document.addEventListener) { // A fallback to window.onload, that will always work window.addEventListener("load", jQuery.ready, false); // If IE event model is used } else { // A fallback to window.onload, that will always work window.attachEvent("onload", jQuery.ready); }
2. DOMContentLoaded event
However, the onload event will not be triggered until all page elements are loaded, including images on the page, etc. If there are a large number of pictures on the web page, the effect can be imagined. The user may have started to operate the page before seeing the pictures. At this time, our page has not been initialized and the event has not been registered. Isn't this right? It's too late!
In addition to the well-known onload event, which is similar to the onload event in DOM, we also have the DOMContentLoaded event to consider. Standard-based browsers support this event. This event will be triggered when all DOM is parsed.
In this way, for standards-based browsers, we can also register the handling of this event. In this way, we may catch the loading completion event earlier.
if (document.addEventListener) { // Use the handy event callback document.addEventListener("DOMContentLoaded", DOMContentLoaded, false); // A fallback to window.onload, that will always work window.addEventListener("load", jQuery.ready, false); }
3. onreadystatechange event
What to do with non-standard browsers?
If the browser has a document.onreadystatechange event, when the event is triggered, if document.readyState=complete, it can be considered that the DOM tree has been loaded.
However, this event is not very reliable. For example, when there are images in the page, it may not be triggered until after the onload event. In other words, it can only be executed correctly when the page contains no binary resources or very few or is cached. As an alternative.
if (document.addEventListener) { // Use the handy event callback document.addEventListener("DOMContentLoaded", DOMContentLoaded, false); // A fallback to window.onload, that will always work window.addEventListener("load", jQuery.ready, false); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent("onload", jQuery.ready); }
What is the DOMContentLoaded function doing? Finally, the jQuery.ready function needs to be called.
DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }
4. doScroll detection method
MSDN has an inconspicuous saying about a JScript method. When the page DOM is not loaded, an exception will be generated when the doScroll method is called. Then we use it in reverse. If there is no exception, then the page DOM has been loaded!
Diego Perini in 2007 reported a way to detect whether IE is loaded, using the doScroll method call. Detailed instructions can be found here.
The principle is that when IE is in a non-iframe, it can only continuously judge whether the DOM is loaded by whether it can execute doScroll. In this example, try to execute doScroll every 50 milliseconds. Note that calling doScroll will cause an exception when the page is not loaded, so try -catch is used to catch the exception.
(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); } // and execute any waiting functions jQuery.ready(); } })();
5. document.readyState 状态
如果我们注册 ready 函数的时间点太晚了,页面已经加载完成之后,我们才注册自己的 ready 函数,那就用不着上面的层层检查了,直接看看当前页面的 readyState 就可以了,如果已经是 complete ,那就可以直接执行我们准备注册的 ready 函数了。不过 ChrisS 报告了一个很特别的错误情况,我们需要延迟一下执行。
setTimeout 经常被用来做网页上的定时器,允许为它指定一个毫秒数作为间隔执行的时间。当被启动的程序需要在非常短的时间内运行,我们就会给她指定一个很小的时间数,或者需要马上执行的话,我们甚至把这个毫秒数设置为0,但事实上,setTimeout有一个最小执行时间,当指定的时间小于该时间时,浏览器会用最小允许的时间作为setTimeout的时间间隔,也就是说即使我们把setTimeout的毫秒数设置为0,被调用的程序也没有马上启动。
这个最小的时间间隔是多少呢?这和浏览器及操作系统有关。在John Resig的新书《Javascript忍者的秘密》一书中提到
Browsers all have a 10ms minimum delay on OSX and a(approximately) 15ms delay on Windows.(在苹果机上的最小时间间隔是10毫秒,在Windows系统上的最小时间间隔大约是15毫秒),另外,MDC中关于setTimeout的介绍中也提到,Firefox中定义的最小时间间隔(DOM_MIN_TIMEOUT_VALUE)是10毫秒,HTML5定义的最小时间间隔是4毫秒。既然规范都是这样写的,那看来使用setTimeout是没办法再把这个最小时间间隔缩短了。
这样,通过设置为 1, 我们可以让程序在浏览器支持的最小时间间隔之后执行了。
// 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") { // 延迟 1 毫秒之后,执行 ready 函数 setTimeout(jQuery.ready, 1); }
6. 完整的代码
在 jQuery 中完整的代码如下所示。位于 jQuery 1.8.3 源代码的 #842 行。
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, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // 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 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); };
那么,又是谁来调用呢?当然是需要的时候,在我们调用 ready 函数的时候,才需要注册这些判断页面是否完全加载的处理,这段代码在 1.8.3 中位于代码的 #244 行,如下所示:
ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }
在页面上引用 jQuery 脚本库之后,执行了 jQuery 的初始化函数,初始化函数中创建了 ready 函数。我们在通过 ready 函数注册事件处理之前,jQuery 完成了页面检测代码的注册。这样。当页面完全加载之后,我们注册的函数就被调用了。
补充:jquery ready 简写模式
Jquery ready 函数:
$(document).ready(function(){ alert(' i am ready'); } );
可简写为:
$(function(){ alert("i am in"); } );
希望本文所述对大家jQuery程序设计有所帮助。