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

后端 未结 6 1555
鱼传尺愫
鱼传尺愫 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:32

    I got an official answer from one of the jQuery developers:

    $().ready(fn) only works because $() used to be a shortcut to $(document) (jQuery <1.4)
    So $().ready(fn) was a readable code.

    But people used to do things like $().mouseover() and all sorts of other madness.
    and people had to do $([]) to get an empty jQuery object

    So in 1.4 we changed it so $() gives an empty jQuery and we just made $().ready(fn) work so as not to break a lot of code

    $().ready(fn) is literally now just patched in core to make it work properly for the legacy case.

    The best place for the ready function is $.ready(fn), but it's a really old design decision and that is what we have now.


    I asked him:

    Do you think that $(fn) is more readable than $().ready(fn) ?!

    His answer was:

    I always do $(document).ready(fn) in actual apps and typically there's only one doc ready block in the app it's not exactly like a maintenance thing.

    I think $(fn) is pretty unreadable too, it's just A Thing That You Have To Know Works™...

提交回复
热议问题