jquery Implementation Dom Loading method source code Analysis

Source: Internet
Author: User
Tags html page instance method ticket

The traditional method of judging Dom loading





Using the Dom0-level onload event to trigger all browsers are supported in the original is very popular writing we are familiar with this writing:





Window.onload=function () {





...


}





But the OnLoad event triggers too slowly, especially when there are a lot of external pictures or video files, and in order to better understand this, it is necessary to know how an HTML document is loaded, citing a friend's statement:





1. User input URL (if it is an HTML page, and is the first access), the browser to the server to send a request, the server returned HTML file;





2. The browser starts loading the HTML code, discovers <head> the label has a <link> tag to refer to the external CSS file;





3. The browser also issued a CSS file request, the server returned to this CSS file;





4. The browser continues to load the HTML <body> part of the code, and the CSS file has been handed, you can start rendering the page;





5. The browser finds a <img> tag in the code that references a picture and makes a request to the server. At this point the browser will not wait until the picture is downloaded, but continue to render the following code;





6. The server returns the picture file, because the picture occupies a certain area, affects the arrangement of the following paragraphs, so the browser needs to go back to render this part of the code;





7. The browser found a <script> tag containing a line of JavaScript code, run it quickly;





The 8.Javascript script executes this statement, which commands the browser to hide a <div> (style.display= "None") in the code. Cup, Ah, suddenly less such an element, the browser has to recreate this part of the code;





9. Finally waiting for the arrival of </html>, browser tears ...





10. Wait, not finished, the user click on the interface of the "Skin" button, JavaScript let the browser change the <link> label CSS Path;





11. The browser has assembled all the <div><span><ul><li> in this room, "Everyone pack up, we have to start again ...", the browser to the server request a new CSS file, to render the page again.





You can see that the first load of the DOM structure after the use of resources such as an IMG tag, the browser reload the IMG tag will not wait until the src corresponding picture load completed will execute the following code, and the onload must wait until all the resources loaded to complete will trigger, So domcontentloaded instead of onload. But for IE low version browsers This method has not yet been implemented, then how to achieve a perfect judge Dom load it? Here's a look at the jquery notation:








using jquery for development





<span style= "FONT-SIZE:16PX; font-family: ' Microsoft Yahei '; >$ (function () {


...


})





Or





$ (doucment). Ready (function () {


...


}) </span>





In a later analysis, you will find that there is no difference between the two, and here is a step-by-step understanding of jquery's writing from this portal:








Source Analysis








First, $ (FN) is passed a function in the constructor in the Init function





HANDLE: $ (function)


Shortcut for document ready


else if (jquery.isfunction (selector)) {


return Rootjquery.ready (selector);


}





If a function is passed, the Rootjquery.ready (selector) is executed; What is Rootjquery?





All JQuery objects should point


Rootjquery = jQuery (document);








is actually $ (document), and then executes a prototype method ready the function as a parameter, OK now shift the line of sight to the ready (this method is a prototype method and tool method do not confuse)





Ready:function (FN) {


Attach the Listeners


Jquery.bindready ();





Add the callback


Readylist.add (FN);





return this;


},











FN accepts the passed in function first executes a tool method Bindready, the line of sight then shifts








Bindready:function () {


if (readylist) {


Return


}





Readylist = Jquery.callbacks ("Once Memory");





Catch cases where $ (document). Ready () is called


Browser event has already occurred.


if (document.readystate = = "complete") {


Handle it asynchronously to allow scripts the opportunity to delay ready


Return settimeout (Jquery.ready, 1);


}





Mozilla, Opera and WebKit nightlies currently support this event


if (Document.addeventlistener) {


Use the handy event callback


Document.addeventlistener ("domcontentloaded", domcontentloaded, false);





A fallback to window.onload, that'll always work


Window.addeventlistener ("Load", Jquery.ready, false);





If IE event model is used


else if (document.attachevent) {


Ensure firing before onload,


Maybe late but safe also for IFRAMEs


Document.attachevent ("onReadyStateChange", domcontentloaded);





A fallback to window.onload, that'll always work


Window.attachevent ("onload", Jquery.ready);





If IE and not a frame


Continually check to-if the document is ready


var toplevel = false;





try {


TopLevel = Window.frameelement = = NULL;


catch (e) {}





if (Document.documentElement.doScroll && toplevel) {


Doscrollcheck ();


}


}


},











This method seems to be complicated, hehe don't be anxious to see the line we are now analyzing the route is $ (FN)->$ (document). Ready->$.bindready





if (readylist) {


Return


}








Here comes a new variable readylist the first time it was executed, because only the declaration was not initialized it must be undefined.





The deferred used on DOM ready


Readylist,








Readylist = Jquery.callbacks ("Once Memory");











And then assign readylist to the value of a callback object. The method for the jquery callback object is no longer in the details, the callback object is created but there is no callback method added at this time.





Catch cases where $ (document). Ready () is called


Browser event has already occurred.


if (document.readystate = = "complete") {


Handle it asynchronously to allow scripts the opportunity to delay ready


Return settimeout (Jquery.ready, 1);


}





Document.readystate represents the state of the document loading, if the load is completed, you can execute the ready method directly, which is also the callback function that executes the pass, now that it has been recorded, it can be executed directly, and using settimeout is the guarantee that the function can be loaded asynchronously





The next thing is to use the Dom2 level event handler to monitor the OnLoad event and domcontentloaded since the latter load faster than the former why is it superfluous? This is because the browser may cache event handlers the onload may be cached and executed first so write who triggers first and who executes first;


But for domcontentloaded is the domcontentloaded method of execution rather than the Ready method, the Domcontentloaded method is also the final implementation ready method:











Cleanup functions for the document Ready method


if (Document.addeventlistener) {


domcontentloaded = function () {


Document.removeeventlistener ("domcontentloaded", domcontentloaded, false);


Jquery.ready ();


};





else if (document.attachevent) {


domcontentloaded = function () {


Make sure body exi msts, at least, in case IE gets a little overzealous (ticket #5443).


if (document.readystate = = "complete") {


Document.detachevent ("onReadyStateChange", domcontentloaded);


Jquery.ready ();


}


};


}








It's just that after you unbind it and make sure it doesn't happen more than once, there's a special way for IE to detect if the scroll bar is possible to perform without the frames page, because if the DOM structure is loaded, the body has a scroll bar.





if (Document.documentElement.doScroll && toplevel) {


Doscrollcheck ();


}














The DOM ready check for Internet Explorer


function Doscrollcheck () {


if (Jquery.isready) {


Return


}


try {


If IE is used with the trick by Diego Perini


http://javascript.nwbox.com/IEContentLoaded/


Document.documentElement.doScroll ("left");


catch (e) {


SetTimeout (Doscrollcheck, 1);


Return


}





and execute any waiting functions


Jquery.ready ();


}











IsReady is to determine whether the state value has been loaded only after the execution of the Ready tool method will become true, and then the continuous detection of scroll bar straight without error The implementation of the Ready method;





So the Bindready method is a preparation method, which binds the function to be executed in the callback function and determines when the trigger is to be triggered, and finally executes the $.ready method note that the Ready method is different from the Ready prototype method or instance method described above.





You'll see that the function is triggered, but don't worry. Add FN to the callback function list, and then we'll go back to the ready instance method after we've read the Bindready.








Ready:function (FN) {


Attach the Listeners


Jquery.bindready ();





Add the callback


Readylist.add (FN);





return this;


},











The original is added here because the Bindready call in the Jquery.ready is asynchronous so the full add operation can be done before execution, now look at the last tool method ready? Of course not, you still have to wait until another method Holdready








Hold (or release) the Ready event


Holdready:function (Hold) {


if (hold) {


jquery.readywait++;


} else {


Jquery.ready (TRUE);


}


},











Not much code is mainly to prevent the callback function trigger, such as we need to load a script file in the middle of the code and want to take precedence over the Rady event execution can use this method to stop execution before resuming implementation dynamic script load parameter is False if not transmitted is the Organization ready event if incoming is unblock , the preparations are finally complete the following begins to look at the Jquery.ready method:








Handle the DOM is ready


Ready:function (Wait) {


Either a released hold or a Domready/load event and not yet ready


if (wait = = True &&!--jquery.readywait) | | (Wait!== true &&!jquery.isready)) {


Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).


if (!document.body) {


Return settimeout (Jquery.ready, 1);


}








This method accepts a parameter, which is Holdready may pass in true, this restricts two conditions to continue to run 1,wait is true readywait minus one 0,readywait is a counter because Holdready can execute multiple times, I didn't do it once. This value minus one 2,wait is not true and Isread is false because IsReady can be modified to ture only after executing to this if statement so this is guaranteed not to be repeated. Under normal circumstances (no call to Holdready) are available, if the call and the presence of a wait statement is lifted, but if the number of lifting is lower than the number of blocking or not;





If it comes in, it's an If. Here is a bug for IE that you can ignore and be interested in looking at jquery's official website description http://bugs.jquery.com/ticket/5443 below can make IsReady true.








Remember that the DOM is ready


Jquery.isready = true;





If a normal DOM Ready event fired, decrement, and wait if need to be


if (wait!== true &&--jquery.readywait > 0) {


Return


}








The ready state change does not mean that the callback function can be executed immediately, and in the previous case, the failure to use Holdready and Holdready (false) can only be satisfied isready ture However, if the Holdready does not pass the value of the case, as long as readywait minus one later than 0 or can not perform, but the next time the release IsReady state is True








If There are functions bound, to execute


Readylist.firewith (document, [JQuery]);





Trigger any bound Ready events


if (JQuery.fn.trigger) {


JQuery (document). Trigger ("Ready"). Off ("Ready");


}








The resulting callback object was executed through the Firewith method, and the This is pointed to doument and the jquery is passed in as a parameter. The Ready event is also trigger triggered and then unbound for possible use of the on method binding; This concludes More complex institutions need to look at the source code several times, and finally paste the main source code





Is the DOM ready to be used? Set to True once it occurs.


Isready:false,





A counter to track how many the items to the wait for before


The Ready event fires. #6781


Readywait:1,





Hold (or release) the Ready event


Holdready:function (Hold) {


if (hold) {


jquery.readywait++;


} else {


Jquery.ready (TRUE);


}


},





Handle the DOM is ready


Ready:function (Wait) {


Either a released hold or a Domready/load event and not yet ready


if (wait = = True &&!--jquery.readywait) | | (Wait!== true &&!jquery.isready)) {


Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).


if (!document.body) {


Return settimeout (Jquery.ready, 1);


}


Remember that the DOM is ready


Jquery.isready = true;





If a normal DOM Ready event fired, decrement, and wait if need to be


if (wait!== true &&--jquery.readywait > 0) {


Return


}





If There are functions bound, to execute


Readylist.firewith (document, [JQuery]);





Trigger any bound Ready events


if (JQuery.fn.trigger) {


JQuery (document). Trigger ("Ready"). Off ("Ready");


}


}


},





Bindready:function () {


if (readylist) {


Return


}





Readylist = Jquery.callbacks ("Once Memory");





//


if (document.readystate = = "complete") {


Handle it asynchronously to allow scripts the opportunity to delay ready


Return settimeout (Jquery.ready, 1);


}





Mozilla, Opera and WebKit nightlies currently support this event


if (Document.addeventlistener) {


Use the handy event callback


Document.addeventlistener ("domcontentloaded", domcontentloaded, false);





A fallback to window.onload, that'll always work


Window.addeventlistener ("Load", Jquery.ready, false);





If IE event model is used


else if (document.attachevent) {


Ensure firing before onload,


Maybe late but safe also for IFRAMEs


Document.attachevent ("onReadyStateChange", domcontentloaded);





A fallback to window.onload, that'll always work


Window.attachevent ("onload", Jquery.ready);





If IE and not a frame


Continually check to-if the document is ready


var toplevel = false;





try {


TopLevel = Window.frameelement = = NULL;


catch (e) {}





if (Document.documentElement.doScroll && toplevel) {


Doscrollcheck ();


}


}


},








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.