Home Web Front-end JS Tutorial Detailed explanation of the use of ready() method of jquery event_jquery

Detailed explanation of the use of ready() method of jquery event_jquery

May 16, 2016 pm 03:32 PM
jquery event

In page initialization, $(document).ready(function(){//code}); or $(window).load(function(){//code});

The difference between them is that ready is triggered after the DOM structure is loaded, and load is triggered after the DOM structure, css, js, images, etc. in the page are loaded. Obviously ready is more suitable for page initialization. . But sometimes that's not always the case. Need to look further into its internal mechanisms.

So how does ready internally determine that the DOM structure has been loaded? And how do different browsers judge it?

The answer lies within the jquery code, assuming the version of jquery is jquery-1.11.3.js.

The key code of ready (lines 3507~3566), the key code is marked in red:

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 );

    // Standards-based browsers support DOMContentLoaded
    } else if ( document.addEventListener ) {
      // Use the handy event callback
      document.addEventListener( "DOMContentLoaded", completed, false );

      // A fallback to window.onload, that will always work
      window.addEventListener( "load", completed, false );

    // If IE event model is used
    } else {
      // Ensure firing before onload, maybe late but safe also for iframes
      document.attachEvent( "onreadystatechange", completed );

      // A fallback to window.onload, that will always work
      window.attachEvent( "onload", completed );

      // 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 );
            }

            // detach all dom ready events
            detach();

            // and execute any waiting functions
            jQuery.ready();
          }
        })();
      }
    }
  }
  return readyList.promise( obj );
};

Copy after login

The above code can be divided into two parts when ready is triggered

1. Trigger under standard browser

When the browser is based on a standard browser, the "DOMContentLoaded" event will be triggered after loading the DOM structure. jquery internally uses this event as the trigger source of ready.

document.addEventListener( "DOMContentLoaded", completed, false );

Copy after login

2. Trigger under IE browser

When the browser is IE, because IE (which is so painful and powerful) does not support the "DOMContentLoaded" event, you have to find another way,

        (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 );
            }

            // detach all dom ready events
            detach();

            // and execute any waiting functions
            jQuery.ready();
          }
        })();

Copy after login

The method under IE is to use the "document.documentElement.doScroll("left")" method in the red text of the above code to scroll the page. If it is not loaded, wait for 50 milliseconds and continue scrolling until it scrolls. Then trigger ready.

However, if there is a frame in the page, the window.onload event will be used as the trigger source of ready.

So under IE, when there is a frame in the page, ready will not be triggered until all the content in the page is loaded.

The difference between ready and load events in jQuery

When you use jQuery at work, you must do this before using it:

//document ready
$(document).ready(function(){
  ...code...
})
//document ready 简写
$(function(){
  ...code...
})
Copy after login

Sometimes it is written like this:

//document load
$(document).load(function(){
  ...code...
})
Copy after login

One is ready and the other is load. What is the difference between the two? Let’s talk today.
Which one is executed first, ready or load:

During the interview process, everyone is often asked a question: Which one of ready and load is executed first, and which one is executed later? The answer is that ready is executed first and load is executed later.
Steps for loading DOM documents:

To understand why ready is executed first and load is executed later, we must first talk about the steps of loading DOM documents:

(1) 解析HTML结构。
(2) 加载外部脚本和样式表文件。
(3) 解析并执行脚本代码。
(4) 构造HTML DOM模型。//ready
(5) 加载图片等外部文件。
(6) 页面加载完毕。//load
Copy after login

You should have understood from the above description that ready is executed after step (4) is completed. But load will not be executed until step (6) is completed.

ready event:

The ready event is executed after the DOM structure is drawn. This ensures that even if a large number of media files are not loaded, the JS code can still be executed.

load event:

The load event must wait until all content in the web page is loaded before it is executed. If there are a large number of images in a web page, this situation will occur: the web page document has been rendered, but because the web page data has not been completely loaded, the load event cannot be triggered immediately.

Summary:

I believe everyone already understands the difference between ready and load. In fact, if there are no media files such as pictures in the page, ready and load are almost the same, but it is different if there are files in the page, so it is still recommended for everyone to work on Ready is used in Chinese.

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles