Home Web Front-end JS Tutorial Analysis on the usage of function ready in jquery

Analysis on the usage of function ready in jquery

Jun 25, 2017 am 10:17 AM
jquery function analyze usage

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.
Copy after login

Translated it


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

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
Copy after login

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;   
            }   
        };
Copy after login

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 );   
                }   
            //下面是一些防御性的编程 故此省略        ......
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles