Why is jQuery.ready recommended when it’s so slow?

后端 未结 4 1878
眼角桃花
眼角桃花 2021-01-31 09:07

I have asked a similar question before but I never made my point exactly clear, or at least I think it’s such a relevant question that it’s worth to bring it up and see if anyon

4条回答
  •  庸人自扰
    2021-01-31 09:37

    To the point first:

    No, there is no disadvantage in calling you init before closing the . It will as you have noticed perform better that relying on $.ready() and will also work with all the browsers flawlessly (even on IE).

    Now, there are however reasons to use $.ready(), which in your case they do not probably apply:

    1. $.ready() makes it easy for developers to do stuff in the right order. In particular, the critical thing is to not reference DOM elements that have not been loaded. While this is simple enough, lots of developers still find it confusing. $.ready() is a no-brainer, albeit a slow one.
    2. In you have say several scripts that need to init(), it is not necessarily easy/convenient to manually do that at the end of your body. It requires discipline and knowledge of what these scripts do. In particular you will often see $.ready() in libraries dependent on jQuery, since it makes things work no matter what way developers will use to load the libs.
    3. With Asynchronous Module Definition (for instance require.js) becoming popular as a way to load your javascript, the end of method is not guaranteed.

提交回复
热议问题