Jquery source code DOM loading, jquery source code dom

Source: Internet
Author: User
Tags getscript

Jquery source code DOM loading, jquery source code dom

JQuery version: 2.0.3

Extensions related to DOM Loading

  • IsReady: whether the DOM is loaded (used internally)
  • ReadyWait: number of files waiting for counter (used internally)
  • HoldReady (): delay DOM triggering
  • Ready (): Prepare DOM triggers.
  • JQuery. ready. promise = function () {}; listens to asynchronous DOM operations (used internally)
1. Relationship between $ (function () {}) and native window. onload

This is also frequently asked during interviews. Analyze their differences from the following perspectives

1. execution time

Page loading: First load nodes and then load files, such as imgfiles and flash files.

$ (Function () {}) DOM is loaded and executed. Maybe the content associated with the DOM element is not fully loaded.

Nodes and files such as window. onload are loaded and executed.

Corresponding event listening

JQuery uses the DOMContentLoaded event.

DOMDContentLoaded: native DOM loading event. This event is triggered to indicate that the DOM has been loaded.

I have previously written an article about page loading time analysis.

Onload corresponds to the load event.

2. Number

Window. onload cannot write multiple values, and the subsequent values will overwrite the previous values.

You can write multiple $ (function. Will be executed.

3. Simplified writing

$ (Function () {}) is a simplified method of $ (document). ready (function.

Window. onload is not simplified.

Ii. How does jQurey implement DOM ready

JQuery calls DOMContentLoaded directly to implement DOM ready. But like DOMContentLoaded and onLoad, the browser only executes the command once. How does jQuery determine whether it has been executed? Document. readyState is the basis for determining this.

ReadyState is the document attribute and has three values in total:

  • Loading: The document is being loaded.
  • Interactive: the file has been loaded. Loading css, images, and other resources is in progress.
  • Complete: The file is loaded.

How do I perform callback after judgment? Is to use Promise. JQuery uses a new $. Deferred (promise) object to call back DOM ready.DOMContentLoaded will remove this promise to resolveIn this way, the previously registered callback function is executed, and the newly registered callback will be executed immediately.

But before calling promise, jQuery executes a setTimeout, because jQuery. promise will not generate Asynchronization, which is different from the standard promise specification. All jQuery manually implements setTimeout to implement Asynchronization. In this way, whether the callback registered before the DOM ready or the callback registered after the DOM is usedAsynchronous execution.

Iii. Overall Implementation logic of source code

$ (Fn) ==> new jQuery. fn. init (fn) ==> returns $ (document). ready (fn ). That is to say

  • $ (Function () {}) ="
  • Call $ (document). ready (function () {}) =
  • Equivalent to $ (). ready (fn) instance method =
  • Called jQuery. ready. promise (). done (fn) ="
  • In jQuery. ready. promise, no matter if or else, jQuery. ready () is called and promise = "is returned.
  • In jQuery. ready (), the focus is readyList. resolveWith (document, [jQuery]); completed. Now, you can call fn after DOM is loaded.

 

 

 

IV. Implementation Details 1. Focus: jQuery. ready. promise () method 【 Clever]

If the DOM has been loaded, call jQuery. ready;

If the DOM is not fully loaded, listen to the DOMContentLoaded event and load event, callback completed () when the event occurs, and finally call the jQuery. ready () tool;

Var // A central reference to the root jQuery (document) rootjQuery, // The deferred used on DOM ready readyList; jQuery. ready. promise = function (obj) {if (! ReadyList) {// the first time the readyList is empty, you can enter it. if it does not come in later, you can only execute readyList = jQuery once. deferred (); // Step 1: Create the delayed object if (document. readyState = "complete") {// The mark after DOM loading is completed is document. readyState is complete. If the DOM has been loaded, you can directly call the tool method jQuery. ready. SetTimeout (jQuery. ready); // The timer is added to ensure compatibility with IE} else {// The DOM has not completed loading detection, that is, the DOMContentLoaded event is detected, and the load event is also detected; the callback completed function // Use the handy event callback document. addEventListener ("DOMContentLoaded", completed, false); // A fallback to window. onload, that will always work window. addEventListener ("load", completed, false); // The load event will be cached by Firefox, and the load will be listened to for the first time.} return readyList. promise (obj );};

The completed callback function is as follows, and jQuery. ready () is finally called ().

// The ready event handler and self cleanup method completed = function () {// both The DOMContentLoaded event and The load event will cancel The listening of two events. // jQuery. ready () only triggers document once. removeEventListener ("DOMContentLoaded", completed, false); window. removeEventListener ("load", completed, false); jQuery. ready ();};
2. What does jQuery. ready () tool do?

Perform a test first:

$ (Function (arg) {alert (this); // [object HTMLDocument] alert (arg); // jQuery function })

Perform another test:

In addition to $ (function () {}); $ (document). ready (function () {}), you can also process ready as an event as follows.

<script>$(document).on("ready",function(){    alert(123); //123});</script>

123 is automatically displayed because jQuery (document) is used in jQuery source code ). trigger ("ready "). off ("ready"); to actively trigger the ready event, and then cancel it.

// Handle when the DOM is readyready: function (wait) {// The parameter is related to holdReady // Abort if there are pending holds or we're already ready if (wait === true? -- JQuery. readyWait: jQuery. isReady) {return;} // Remember that the DOM is ready jQuery. isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if (wait! = True & -- jQuery. readyWait> 0) {return;} // For the first step, check the key here. When resolveWith changes the status, the parameter is passed, and the fn parameter is passed to the done method, // document is the this point of fn, and jQuery is the parameter // If there are functions bound, to execute readyList. resolveWith (document, [jQuery]); // related to active triggering // Trigger any bound ready events if (jQuery. fn. trigger) {jQuery (document ). trigger ("ready "). off ("ready ");}},

There is a holdReady () related to the ready parameter ().

Perform a test first

$. HoldReady (true); $ (function () {alert (123); // If holdReady is called and the parameter is set to true, 123 is not displayed });

It can be postponed or released. Once released, it can be triggered.

$. HoldReady (true); $. holdReady (false); $ (function () {alert (123); // If holdReady is released, 123} is displayed });

What is the purpose of this?

For example:

$. GetScript ('js/a. js', function () {// load asynchronously without affecting subsequent code execution. Alert (2) First executes. js has not been loaded yet}) $ (function () {alert (2); // first play 2, then pop up 1 });

Many times, when introducing external files, you want to wait until the external files or plug-ins are loaded to trigger the operation. The operation may use a. js. If the order is incorrect, a problem may occur.

How can this problem be solved? Use the holdReady () method.

$. HoldReady (true); // hold $ first here. getScript ('js/. js', function () {// asynchronous loading does not affect subsequent code execution. Alert (2) First executes. js has not been loaded yet $. holdReady (false); // after loading and releasing, you can play 2 if you don't hold it.}) $ (function () {alert (2); // first play 2, pop up 1 });

Further down, there may be more than one file to be targeted by holdReady (), so it is necessary to wait until all the files are loaded before execution. Therefore, there is a counting readyWait in the source code.

The source code defines a variable waiting for the stack -- readyWait, each execution of $. holdReady (true) will increase the pressure stack, and every time $. the execution of holdReady () will play the stack, and jQuery will be executed when there is no stack. the ready function, which is about to release promise to resolve.

// Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. see #6781 readyWait: 1, // check the second step here // holdReady delays DOM triggering // Hold (or release) the ready eventholdReady: function (hold) {if (hold) {jQuery. readyWait ++; // hold is true, so that readyWait can be added for processing} else {jQuery. ready (true) ;}}, // Handle when the DOM is readyready: function (wait) {// parameters and holdReady // Abort if there are pending holds or we're already ready // when readyWait is 0, do not hold it. Execute the following operation if (wait = true? -- JQuery. readyWait: jQuery. isReady) {return;} // Remember that the DOM is ready jQuery. isReady = true; // The default value is false. // If a normal DOM Ready event fired, decrement, and wait if need be if (wait! = True & -- jQuery. readyWait> 0) {return;} // For the first step, check the key here. When resolveWith changes the status, the parameter is passed, and the fn parameter is passed to the done method, // document is the this point of fn, and jQuery is the parameter // If there are functions bound, to execute readyList. resolveWith (document, [jQuery]); // related to active triggering // Trigger any bound ready events if (jQuery. fn. trigger) {jQuery (document ). trigger ("ready "). off ("ready ");}},

 

At the beginning, I started to look at the source code, and I may not understand it in many places.

 

Refer:

Http://www.cnblogs.com/aeexiaoqiang/p/6525702.html

 

Starof, the author of this article, is constantly learning and growing because of the changing knowledge. The content of this article is also updated from time to time. To avoid misleading readers and facilitate tracing, Please repost the Source: Ghost.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.