Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.ready() before closing body

This is not a real coding question, more of a real-world statement.

I have previously noted that DOMReady events are slow, very slow. So, I noticed while browsing the jQuery source that the jQuery domeready event can be trigger using $.ready(). Then I thought, placing this simple execution script just before closing the body should trigger all the "onDomReady" listeners that where previoulsy attached. And yes, it works as expected:

     <script>$.ready()</script>
</body>

Here are two examples, this one measures the ms spent while waiting for DOMReady:

http://jsbin.com/aqifon/10

As you can see, the DOMReady trigger is very natively slow, the user has to wait for a whole 200-300 milliseconds before the domready script kick in.

Anyway, if we place $.ready() just before closing the BODY tag we get this:

http://jsbin.com/aqifon/16

See the difference? By triggering domready manually, we can cut off 100-300 ms of execution delay. This is a major deal, because we can rely on jQuery to take care of DOM manipulations before we see them.

Now, to a question, I have never seen this being recommended or discussed before, but still it seems like a major performance issue. Everything is about optimizing the code itself, which is good of course, but it is in vain if the execution is delayed for such a long time that the user sees a "flash of "unjQueryedContent".

Any ideas why this is not discussed/recommended more frequently?

like image 837
David Hellsing Avatar asked Oct 12 '12 00:10

David Hellsing


1 Answers

By triggering the event yourself, you are stating to your ready() handlers that your dom has been loaded BUT it may not have been! There is no short cutting the DOM ready event. If there is indeed a long wait time, then employ the amazing debugging tools of firebug, chrome, etc.... check your resources and their timing ques. It's all there in black and white and will indicate what is taking so long (the requests, the rendering, how many resources, etc.. )

like image 160
ilan berci Avatar answered Oct 03 '22 08:10

ilan berci