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

元气小坏坏 提交于 2019-12-02 17:05:49

To the point first:

No, there is no disadvantage in calling you init before closing the <body>. 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 <body/> method is not guaranteed.

One advantage would be, that you are able to place the code anywhere in the page. In our case, we use a templating system in our CMS that stitches the page together from around 10 - 30 templates for the different parts (depending on complexity).

Since you want the templates to work on any page they are used, you need to include the necessary Javascript in it. For those cases, the ready() function is a real life saver.

If you've written a JS file that other people are including in their pages it is safer to use document.ready within that file (assuming it needs to do some processing automatically after the DOM is ready) because you can't be sure whether the file will be included in the head or at the end of the body.

When it comes to pages that you have complete control over then obviously you don't have that worry, so I don't see that it is any more "safe" to use document.ready rather than calling your init() from the end of the body. Using document.ready (or onload) and putting script at the end of the body are the two most common ways to do it, and they're common because they both work well.

You mentioned document.write() as a possible exception, but you don't want to be calling that from document.ready or at the end of the body because either way the whole page has already been parsed.

Because it makes domReady and window.load slower.

It's easy to optimize to the metric, rather than the actual user experience. So the "real user optimization" graphs go down, even though interactivity is delayed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!