This article will introduce jQuery ready and window. onload usage to you. If you are interested, please refer to it.
I recently worked on a project and wrote a plug-in the previous article: jQuery rolling fixed plug-in. I tested it locally at the beginning and found it was okay. Then I set it up on the server, it is found that the final position of the float is always incorrect. I thought it was a code conflict or the plug-in was not well written. Later I started debugging. We found that the height of the Bottom parameter is changing with the refreshing of the browser, which is impossible. The elements are fixed there. I didn't think it was the reason for jQuery.
Take a browser to load documents as an example. After a page is loaded, the browser adds an event to the DOM element through Javascript. In common Javascript code, window is usually used. onload method, while in Jquery, $ (document) is used ). ready () method. Because the event registered in the $ (document). ready () method is executed as long as the DOM is ready, the associated file of the element may not be downloaded at this time. For example, html related to the image has been downloaded and parsed as a DOM tree. However, it is very likely that the image has not been loaded, and the height and width of the image are not necessarily valid. To solve this problem, you can use the load () method, another method for page loading in Jquery. The Load () method binds a handler to the onload event of the element.
If the processing function is bound to a window object, it is triggered after all the content (including the window, frame, object, and image) is loaded. If the processing function is bound to an element, it is triggered after the element content is loaded.
The following describes the differences between jQuery ready and window. onload.
|
Window. load |
$ (Document). ready () |
Execution time |
You must wait until all the content on the webpage is loaded (including images ). |
After all DOM structures in the webpage are drawn, they can be executed. The content associated with DOM elements is not loaded completely. |
Write count |
The following code cannot be written at the same time and cannot be correctly executed: window. onload = function () {alert ("caibaojian") ;}; window. onload = function () {alert ("caibaojian.com") ;}; only the second |
You can write the following code correctly: $ (document ). ready (function () {alert ("Hello Caibaojian") ;}); $ (document ). ready (function () {alert ("Hello caibaojian.com") ;}); both results are output |
Simplified writing |
None |
$ (Function () {// do something }); |
The Jquery code is as follows:
When the jquery script is loaded, an isReady flag is set to listen to the DOMContentLoaded event (this is not available in all browsers. jquery works differently in different browsers ). of course, when calling the ready function, if isReady is not set, it means that the page is not loaded, and the function to be executed will be cached in an array. After the page is loaded, then execute the cached functions one by one.
Detailed code analysis in Jquery:
The Code is as follows: |
Copy code |
Ready: function (fn ){ // Bind the listener BindReady (); // If DOM loading is complete If (jQuery. isReady) // Run this function immediately Fn. call (document, jQuery ); // Otherwise, save it Else // Add the function to the cache Array JQuery. readyList. push (function () {return fn. call (this, jQuery );}); Return this; }
|
Let's take a look at jquery's bindReady () function for notifications of dom loading completion in different browsers:
The Code is as follows: |
Copy code |
Var readyBound = false; Function bindReady (){ If (readyBound) return; ReadyBound = true; // Mozilla, opera, and webkitnightlies support DOMContentLoaded events If (document. addEventListener &&! JQuery. browser. opera) // Directly use Event Callback. Document. addEventListener ("DOMContentLoaded", jQuery. ready, false ); // If it is ie and is not embedded in the frame // You need to constantly check whether the document has been loaded. If (jQuery. browser. msie & window = top) (function (){ If (jQuery. isReady) return; Try { // Mark this place and parse it later (1) Document.doc umentElement. doScroll ("left "); } Catch (error ){ /// Mark this place and parse it later (2) SetTimeout (arguments. callee, 0 ); Return; } // And execute any waiting functions JQuery. ready (); })(); If (jQuery. browser. opera) Document. addEventListener ("DOMContentLoaded", function (){ If (jQuery. isReady) return; For (var I = 0; I <document. styleSheets. length; I ++) // mark (3) If (document. styleSheets [I]. disabled ){ SetTimeout (arguments. callee, 0 ); Return; } // And execute any waiting functions JQuery. ready (); }, False ); If (jQuery. browser. safari ){ Var numStyles; (Function (){ If (jQuery. isReady) return; If (document. readyState! = "Loaded" & document. readyState! = "Complete") {// mark (4) SetTimeout (arguments. callee, 0 ); Return; } If (numStyles === undefined) NumStyles = jQuery ("style, link [rel = stylesheet]"). length; If (document. styleSheets. length! = NumStyles) {// mark (5) SetTimeout (arguments. callee, 0 ); Return; } // And execute any waiting functions JQuery. ready (); })(); } // A fallback to window. onload, that will always work JQuery. event. add (window, "load", jQuery. ready); // mark (6) } } |
1): This mainly measures dom ready in ie, which can be used in ie.when domis not completed, the document.doc umentElement. doScroll ("left") of documentwill be used to identify whether the dom has ready.
(2): setTimeout (arguments. callee, 0) indicates that the call is delayed by 0 seconds. In fact, it will not be called immediately, but will be called as soon as possible, it tells the browser to run the event handle for any pending event and update the current state of the document before calling. arguments. callee is the anonymous function of the outer layer. The caller of the Parameter
(3): You may find it strange. Why isn't it handled together by mozilla? The reason is that after the DOMContentLoaded event of opera occurs, its css style is not fully available yet, so special processing is required to determine whether each css tag is enable.
(4), (5): When the status of document. readyState in safari is loaded or complete, the introduction of the css file fails to determine whether it is parsed. Therefore, you need to determine the number of css files.
(6): Finally, if none of the above hack is supported... Use the safest load event to ensure that the initialization code can be executed.