Why “$().ready(handler)” is not recommended?

后端 未结 6 1543
鱼传尺愫
鱼传尺愫 2020-11-27 13:30

From the jQuery API docs site for ready

All three of the following syntaxes are equivalent:

  • $(document).ready(handle
6条回答
  •  再見小時候
    2020-11-27 14:20

    Since the different options do pretty much the same thing as you point out, it's time to put on the library writer hat and make some guesses.

    1. Perhaps the jQuery people would like to have $() available for future use (doubtful since $().ready is documented to work, even if not recommended; it would also pollute the semantics of $ if special-cased).

    2. A much more practical reason: the second version is the only one that does not end up wrapping document, so it's easier to break when maintaining the code. Example:

      // BEFORE
      $(document).ready(foo);
      
      // AFTER: works
      $(document).ready(foo).on("click", "a", function() {});
      

      Contrast this with

      // BEFORE
      $().ready(foo);
      
      // AFTER: breaks
      $().ready(foo).on("click", "a", function() {});
      
    3. Related to the above: ready is a freak in the sense that it's (the only?) method that will work the same no matter what the jQuery object wraps (even if it does not wrap anything as is the case here). This is a major difference from the semantics of other jQuery methods, so specifically relying on this is rightly discouraged.

      Update: As Esailija's comment points out, from an engineering perspective ready should really be a static method exactly because it works like this.

    Update #2: Digging at the source, it seems that at some point in the 1.4 branch $() was changed to match $([]), while in 1.3 it behaved like $(document). This change would reinforce the above justifications.

提交回复
热议问题