Home  >  Article  >  Web Front-end  >  Analysis on the usage of function ready in jquery

Analysis on the usage of function ready in jquery

巴扎黑
巴扎黑Original
2017-06-25 10:17:441466browse

Recently I read some comments about jquery ready. Some people say it is slow, some people say it is fast. There are different opinions. So I did some in-depth research myself. First, I took a look at the description of ready in the jquery document


While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

Translated it


虽然JavaScript提供了load事件,当页面渲染完成之后会执行这个函数,在所以元素加载完成之前,这个函数不会被调用,例如图像。但是在大多数情况下,只要DOM结构加载完,脚本就可以尽快运行。传递给.ready()的事件句柄在DOM准备好后立即执行,因此通常情况下,最好把绑定事件句柄和其他jQuery代码都到这里来。但是当脚本依赖于CSS样式属性时,一定要在脚本之前引入外部样式或内嵌样式的元素。   
  
如果代码依赖于需加载完的元素(例如,想获取一个图片的尺寸大小),应该用.load()事件代替,并把代码放到load事件句柄中。

According to the instructions in the document, When there are a large number of document structures and image resources in the page, ready is faster than load. The document also clearly analyzes when to use ready and when to use load.

Let’s analyze the running process of jquery ready


$(handler) or $(document).ready(handler) →  ready() → bindReady() → 执行readyList.add( fn ) fn

Take a rough look at the source code

The following is the object of jqueryready source code


 jQuery.fn = jQuery.prototype = {   
            constructor: jQuery,   
            init: function( selector, context, rootjQuery ) {   
                // HANDLE: $(function)   
                // Shortcut for document ready   
                // 如果函数,则认为是DOM ready句柄   
                if ( jQuery.isFunction( selector ) ) {   
                    return rootjQuery.ready( selector );   
                }   
            },   
           
            ready: function( fn ) {   
                // Attach the listeners   
                jQuery.bindReady(); // 绑定DOM ready监听器,跨浏览器,兼容标准浏览器和IE浏览器   
           
                // Add the callback   
                     readyList.add( fn );// 将ready句柄添加到ready异步句柄队列   
           
                return this;   
            }   
        };

Call jquery’s bindReady and add ready callback!

Let’s take a look The approximate source code of bindReady


    bindReady: function() { // jQuery.bindReady   
                if ( readyList ) {   
                    return;   
                }   
  
                readyList =jQuery.Callbacks( "once memory" )// 初始化ready异步事件句柄队列   
  
                // Catch cases where $(document).ready() is called after the   
                // browser event has already occurred.   
                // 如果DOM已经完毕,立即调用jQuery.ready   
                if ( document.readyState === "complete" ) {   
                    // Handle it asynchronously to allow scripts the opportunity to delay ready   
                    // 重要的是异步   
                    return setTimeout( jQuery.ready, 1 );   
                }   
            //下面是一些防御性的编程 故此省略        ......
}

This should be very clear. document.readyState == 'complete' will execute jquery's ready. I am confused as to why. It is setTiemout(jQuery.ready,1). Please return to the ready code above, readyList.add(fn). If it is not asynchronous, the execution of the callback will be placed before readyList.add(fn), because the execution is before In jQuery's ready readyList.fireWith(document, [jQuery]);readylist is jquery's callbacks, which manages the callback function! If you are not sure, you can read the documentation.

Note: You will find that there are two readys. These two are different. One is placed in jquery.prototype and is our $(document).ready. The other is jquery’s object method to determine whether it is ready. The method

ps: jquery is profound and profound. If there are any errors in the article, please correct me!

The above is the detailed content of Analysis on the usage of function ready in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn