How does jQuery implement domReady and onload judgment?

Source: Internet
Author: User

How does jQuery implement domReady and onload judgment?

We are familiar with the $ (function () {}) form in jQuery usage. We bind the event function to the moment when the dom is loaded, relative to the window. in onload, some images, dynamic scripts, and some external resources can be avoided, which may cause a large delay impact on the current code execution because of window. onload is triggered only after all the resources to be loaded on the current page are loaded, including the dynamic loading before onload is triggered.

For standard browsers, The DOMContentLoaded event is used as an event triggered after dom loading, of course, to be accurate, it is triggered when dom and non-Dynamically Loaded JS are loaded. (For details about the triggering time, see the impact of JS, CSS, and img on the DOMContentLoaded event ).

Of course, earlier versions of IE (IE6 ~ IE8) does not support DOMContentLoaded events, so you also need to use some other methods to simulate DOMContentLoaded time triggering. Currently, the mainstream earlier version of the IE simulation method is to use doScroll for loop judgment. For JScript, if doScroll is called when the dom is not loaded, an error is reported, and try catch is used for Round Robin determination.

So we need to know how jQuery distinguishes domReady from load, that is, how jQuery implements domReady, because onload is an event that has been implemented by various browsers, DOMContentLoaded is not implemented by earlier IE versions. Then the jQuery version used this time is 1.11. After all, it also includes the following earlier versions of IE, SO 2 is not used. * version, but the essence is the same, only 2. * In versions, doScroll is discarded for loop determination and earlier version IE is abandoned. The best way to understand the essence is to look at the jQuery source code.

 
 
  1. // A jQuery deferred of DOM ready
  2. // It is also used as the tag for binding initialization.
  3. Var readyList;

  4. // Call the binding before binding initialization.
  5. JQuery. fn. ready = function (fn ){
  6. // Initialization binding is performed only when Initialization is not performed.
  7. JQuery. ready. promise (). done (fn );
  8. Return this;
  9. };

  10. JQuery. extend ({
  11. // Whether the tag is triggered by DOM ready
  12. IsReady: false,
  13. ReadyWait: 1,

  14. HoldReady: function (hold ){
  15. If (hold ){
  16. JQuery. readyWait ++;
  17. } Else {
  18. JQuery. ready (true );
  19. }
  20. },

  21. // DOM ready event handle
  22. Ready: function (wait ){

  23. If (wait === true? -- JQuery. readyWait: jQuery. isReady ){
  24. Return;
  25. }

  26. // The small BUG of IE ensures that the body already exists
  27. If (! Document. body ){
  28. Return setTimeout (jQuery. ready );
  29. }

  30. // Switch the label status
  31. JQuery. isReady = true;

  32. // Whether the tag needs to be waited
  33. If (wait! = True & -- jQuery. readyWait> 0 ){
  34. Return;
  35. }

  36. // Execute ready binding in the form of jquery
  37. ReadyList. resolveWith (document, [jQuery]);

  38. // Trigger other binding forms at the same time and log out in time
  39. If (jQuery. fn. triggerHandler ){
  40. JQuery (document). triggerHandler ("ready ");
  41. JQuery (document). off ("ready ");
  42. }
  43. }
  44. });

The extended isReady is used to control the number of ready executions. readyWait and holdReady are not included in this article. The ready method is the core and is triggered when jQuery determines domReady, combined with the resolveWith of defferred, event handles stored in the cache event handle array are executed one by one. The next step is domReady, which determines the domReady moment.

 
 
  1. // Remove all binding events related to the event handle compeleted
  2. Function detach (){
  3. If (document. addEventListener ){
  4. Document. removeEventListener ("DOMContentLoaded", completed, false );
  5. Window. removeEventListener ("load", completed, false );
  6. } Else {
  7. Document. detachEvent ("onreadystatechange", completed );
  8. Window. detachEvent ("onload", completed );
  9. }
  10. }

  11. // For A domReady time point that has passed
  12. Function completed (){
  13. // The standard browser, the load event in IE, or the ready state is complete (IE)
  14. If (document. addEventListener | event. type = "load" | document. readyState = "complete "){
  15. Detach ();
  16. JQuery. ready ();
  17. }
  18. }

  19. JQuery. ready. promise = function (obj ){
  20. If (! ReadyList ){
  21. // Initialize readyList
  22. ReadyList = jQuery. Deferred ();

  23. // When $ (document). ready () is called after the ready event, it is directly triggered.
  24. If (document. readyState = "complete "){
  25. // Execute Similar simulated event triggers in asynchronous mode
  26. SetTimeout (jQuery. ready );

  27. // DOMContentLoaded event binding
  28. } Else if (document. addEventListener ){
  29. Document. addEventListener ("DOMContentLoaded", completed, false );
  30. Window. addEventListener ("load", completed, false );

  31. // This is the earlier version of IE.
  32. } Else {
  33. Document. attachEvent ("onreadystatechange", completed );
  34. Window. attachEvent ("onload", completed );

  35. // IE doScroll Detection
  36. Var top = false;

  37. Try {
  38. Top = window. frameElement = null & document.doc umentElement;
  39. } Catch (e ){}

  40. If (top & top. doScroll ){
  41. (Function doScrollCheck (){
  42. If (! JQuery. isReady ){
  43. Try {
  44. Top. doScroll ("left ");
  45. } Catch (e ){
  46. // When an error occurs in try, the next latency loop is detected.
  47. Return setTimeout (doScrollCheck, 50 );
  48. }

  49. Detach ();
  50. JQuery. ready ();
  51. }
  52. })();
  53. }
  54. }
  55. }
  56. Return readyList. promise (obj );
  57. };

In fact, for jQuery, it is a bit similar to killing one thousand by mistake and not letting go of one. In any status, you can listen to as many events as possible for judgment. In DOMContentLoaded, load, readystatechange and doScroll loop. jQuery is available. is isReady checked? What are you afraid. For more information about this process, you also need to know about jquery's promise. The functions and source code of jQuery callback and defferred. Why do you want to return readyList. promise (obj)? Let's take a look!






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.