Ready is executed first, load is executed, DOM document loading steps

Source: Internet
Author: User

There are several ways to execute a specified function after the document has been loaded in JQ:

$ (document). Ready (function () {//... Code ...}); Document ready Shorthand $ (function () {//... Code ...}); $ (window). Load (function () {//... Code ...});

$ (function () {}) is in fact a $ (document). Short of Ready () to see the JQ constructor block.

Ready and load who executes first

This issue is also often mentioned during an interview, Ready is executed first, load is executed, and the DOM document is loaded with steps:

(1) parsing the HTML structure. (2) Loading external scripts and style sheet files. (3) Parse and execute script code. (4) Constructs an HTML DOM model. Ready (5) Loads external files such as pictures. (6) The page has finished loading. Load Analysis Reason

. Ready () is a function of the Window.onload event.

JQuery.fn.ready = function (fn) {//ADD the callback JQuery.ready.promise (). Done (FN); return this;};

When the ready event is called, JQ adds the function to a list of callbacks.

and. Load () acts on the Load event binding handler function for each matching element.

$ (window). Load (function () {alert ("Document Loaded!");}); $ ("img"). Load (function () {alert ("picture [" + This.alt + "] loaded complete!");});

Load's writing also changed a bit, after the 1.8 version, load was discarded, only the AJAX load, its function prototype:

jQuery.fn.load = function (URL, params, callback) {//code ... return this;}

It should therefore be used in a higher version:

$ (' #result '). Load (' ajax/test.html ', function () {alert (' load was performed. ');}); Ready source//readylist.promise () = = = JQuery.ready.promise () var readylist; JQuery.fn.ready = function (fn) {///Promise Add Callback JQuery.ready.promise (). Done (FN);//Chain return this;}; Jquery.extend ({//This judgment prevents repeated triggering of isready:false,//requires several jquery.ready () calls before triggering promise and custom ready event readywait:1,//Hold (or Rele ASE) The Ready event Holdready:function (Hold) {if (hold) {//true, delay +1 jquery.readywait++;} else {//no parameters, number of cuts -1 Jquery.ready (TRUE); }},//trigger promise and custom Ready event ready:function (wait) {///Ready (TRUE), where the number of cuts is. can also replace dry ready (wait = = = = true?--jquery.readywait:jquery.isready) {return;}//Ready () when the tag Dom is loaded complete jquery.isre Ady = true; Ready (2881064151) can set IsReady, only the default 1 times if (wait!== true &&--jquery.readywait > 0) {return;}//Trigger Prom Ise,jquery.fn.ready (FN) binding functions are triggered by Readylist.resolvewith (document, [JQuery]); Triggers a custom Ready event and removes the event binding if (JQuery.fn.triggerHandler {jquery (document). Triggerhandler ("Ready"), jquery (document), Off ("Ready"),}} }); Unbind functions function completed () {Document.removeeventlistener ("domcontentloaded", completed, false); Window.removeeventlistener ("Load", completed, false); Jquery.ready (); } jQuery.ready.promise = function (obj) {if (!readylist) {readylist = jquery.deferred ();//To determine if execution has already loaded complete if (doc Ument.readystate = = = "complete") {//no longer need to bind any listener function, directly trigger jquery.ready. Delay a while, and so on after the code executes setTimeout (Jquery.ready); } else {//Use the handy event callback Document.addeventlistener ("domcontentloaded", completed, false);//Individual browser situation, missed Events can still trigger Window.addeventlistener ("Load", completed, false); }} return Readylist.promise (obj); }; Perform. Generate deferred object, bind good listening logic jQuery.ready.promise ();

Readylist = jquery.deferred (); The callback list is $. Deferred object, Event listener through:

Document.addeventlistener ("domcontentloaded", completed, false); Window.addeventlistener ("Load", completed, false);

To achieve compatibility with different browsers, one added to the window one adds to document, avoiding multiple calls through $.isready.

function completed () {Document.removeeventlistener ("domcontentloaded", completed, false); Window.removeeventlistener ("Load", completed, false); Jquery.ready (); }

To unbind an event, call $.ready ():

Readylist.resolvewith (document, [JQuery]);

Executes the function queue in an asynchronous object.

Load

The implementation of load is relatively simple, jQuery.fn.load = function (URL, params, callback) {} It is almost equivalent to $.get (URL, data, success) because it is implemented by $.ajax (), The difference is that its URL can contain a space or multiple spaces, and the string immediately following the first space is the jQuery selector that determines what is loaded:

$ ("#result"). Load ("ajax/test.html #container");

If the method is executed, the contents of the ajax/test.html are retrieved, but then JQuery parses the returned document to find the element with the container ID. The element, along with its contents, is inserted into the element with the result ID, and the remainder of the retrieved document is discarded.

Off = Url.indexof (""); if (off >= 0) {selector = Jquery.trim (Url.slice (off)); url = url.slice (0, off);}

Finally take a look at its Ajax section:

Jquery.ajax ({url:url,//If "type" variable is undefined and then "GET" method would be used Type:type, DataType: "HTML", D Ata:params}). Done (function (responsetext) {//Save response for use in complete callback response = arguments; self.ht ML (selector//If A selector is specified, locate the right elements in a dummy div//Exclude scripts to avoid IE ' Pe Rmission Denied ' Errors jQuery ("<div>"). Append (jquery.parsehtml (responsetext)). Find (Selector)://Otherwise U Se the full result responsetext); }). Complete (callback && function (JQXHR, status) {Self.each (callback, Response | | [Jqxhr.responsetext, status, Jqxhr]); });

Self.html () uses the browser's. InnerHTML property to parse the retrieved document and insert it into the current document.

Ready is executed first, load is executed, DOM document loading steps

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.