We all know that the Window.onload method in JavaScript is inadequate: it must wait until all images and rich text media are loaded before it can be executed, affecting the user experience. It is a better practice to wait until the DOM is loaded to execute the corresponding callback. Similar to jquery, the domready approach emerged.
Using this method in jquery is very simple: $ (function () {}), which is actually $ (document). Easy-to-use notation for Ready (function () {}), see Source code:
Rootjquery = jQuery (document); if (Jquery.isfunction (selector)) { return rootjquery.ready (selector);}
Behind the simple, jquery is encapsulated, masking a lot of compatibility issues. Let's take a look at the native Domready events and learn about the pits.
1,W3C domcontentloaded, it's not easy to say love you.
Originally is a good method, but for ie6,7,8, can only hehe.
2,settimeout
The function set by settimeout is triggered when readystate is complete, but the trigger time is after the picture resource has been loaded.
3,readystate
ReadyState is interactive, the DOM structure is not stable, there will still be scripts to modify the DOM elements, readystate as complete, the picture has been loaded
4, external script (implemented by setting the script's Defer property)
External script: If this script is placed above the page, it cannot be triggered stably. And the DOM structure can still change when triggered.
5,doscroll ( Microsoft's documentation only doscroll must be completed when the DOM main document is ready to trigger normally. So you can determine whether the DOM is ready by DoScroll )
ReadyState may be interactive or complete when DoScroll is passed. However, after the DOM structure is stable, the picture is executed before it is loaded.
A lot of methods, more clutter. jquery's approach is preferable, listening to various trigger conditions. Would rather kill 1000 wrong, never let go of one.
To see the implementation of the source code:
function (FN) { // ADD The callback jQuery.ready.promise (). Done (FN); return This ;},
JQuery.ready.promise is an asynchronous deffered object that triggers the callback FN after completion.
When does the deferred object finish? The best result, of course, is that the DOM is triggered immediately after loading. This time is a variety of monitoring methods.
JQuery.ready.promise =function(obj) {if( !readylist) {Readylist=jquery.deferred (); //Catch cases where $ (document). Ready () was called after the browser event had 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 readysetTimeout (Jquery.ready); //standards-based browsers support domcontentloaded}Else if(document.addeventlistener) {//Use the handy event callbackDocument.addeventlistener ("domcontentloaded", completed,false ); //A fallback to window.onload.Window.addeventlistener ("Load", completed,false ); //If IE event model is used}Else { //ensure firing before onload, maybe late but safe also for IFRAMEsDocument.attachevent ("onReadyStateChange", completed); //A fallback to window.onload.Window.attachevent ("onload", completed); //If IE and not a frame //continually check to see if the document was ready vartop =false; Try{Top= Window.frameelement = =NULL&&document.documentelement; } Catch(e) {}if(Top &&top.doscroll) {(functionDoscrollcheck () {if( !jquery.isready) {Try { //Use the trick by Diego Perini //http://javascript.nwbox.com/IEContentLoaded/Top.doscroll ("left"); } Catch(e) {returnSetTimeout (Doscrollcheck, 50 ); } //Detach all DOM ready eventsdetach (); //and execute any waiting functionsJquery.ready (); } })(); } } } returnreadylist.promise (obj);};
How much to judge, how much to bind ... The first is to Judge Document.readystate. If it is equal to complete, immediately execute back to
Document.readystate = = = "complete"
Depending on the browser, bind separately:
Standard browser bindings: domcontentloaded, binding load
Document.addeventlistener ("domcontentloaded", completed, false)
Window.addeventlistener ("Load", completed, false)
Under IE browser
Document.attachevent ("onReadyStateChange", completed)
Window.attachevent ("Load", completed)
According to Top.doscroll ("left") to determine whether the load is complete, after loading directly triggered: Jquery.ready ();
And look at the completed method.
function (event) { // readyState = = = ' Complete ' is good enough for us to call the DOM ready in oldie if (Document.addeventlistener | | event.type = = = "Load" | | document.readystate = = = "complete" ) { Detach (); Jquery.ready (); }},
or trigger the Jquery.ready. Finally, let's see Jquery.ready.
Readyfunction(wait) {//Abort If there is pending holds or we ' re already ready if(Wait = = =true? --JQuery.readyWait:jQuery.isReady) { return; } //Make sure body exists, at least, with case IE gets a little overzealous (ticket #5443). if( !document.body) {returnsetTimeout (Jquery.ready); } //Remember that the DOM was readyJquery.isready =true; //if a normal DOM ready event fired, decrement, and wait if need is if(Wait!==true&&--jquery.readywait > 0 ) { return; } //If There is functions bound, to executeReadylist.resolvewith (document, [JQuery]); //Trigger any bound ready events if(JQuery.fn.trigger) {jQuery (document). Trigger (' Ready '). Off ("Ready"); }},
Finally, the callback will be triggered: Readylist.resolvewith (document, [JQuery]);
This is the implementation of Domready in jquery. is still more perfect.
The advantage is that after the asynchronous callback is added, the structure is very graceful and where to trigger it. and almost fully compatible.
The disadvantage is that there are too many monitoring methods, the compatibility requirements are not high, do not have such a cost performance method.
Reference Document: Http://www.cnblogs.com/zhangziqiu/archive/2011/06/27/DOMReady.html
The analysis of Domready in jquery