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 anyone can give some insightful thoughts.
When using jQuery, many of us use the jQuery.ready
function to execute an init
when the DOM has loaded. It has become the de-facto standard way of adding DOM manipulation programs to a web page using jQuery. A related event exists natively some browsers, but jQuery emulates it in other browsers, such as some IE versions. Example:
<head>
<script>
var init = function() { alert('hello world'); };
$.ready(init);
</script>
Now, all our tests show that this event can be quite slow. It’s not nearly as slow as window.onload
, but it’s still often around 100 ms delay before execution. If FF it can be up to 200-300 ms, especially on refresh.
These are some very important milliseconds, because this is the amount of time the initial layout is shown before any DOM manipulations are made (such as hiding a dropdown). Many times, a layout "flicker" is mainly caused by using a slow DOM ready event, forcing programmers to hide elements using CSS instead and potentially making it less accessible.
Now if we instead place an init function in a script tag before closing the body tag, it will be executed much faster, usually around half the time but sometimes even faster:
<head>
<script>
var init = function() { alert('hello world'); };
</script>
</head>
<body>
<!-- some HTML -->
<script>init();</script>
</body>
A simple test page that proves the differences: http://jsbin.com/aqifon/10
I mean, we are not talking about barely noticeable differences as some of the "optimization police" promotes when it comes to using effective selectors. We are talking about some major delays when doing DOM manipulations onload. Trying this example in FF, domready can sometimes be more than 100 times slower (300ms vs 2ms).
Now to my question: Why is jQuery.ready
recommended to use when it’s obviously much slower that other alternatives? And what are the drawbacks of calling the init
before closing the BODY vs using jQuery.ready
? It’s arguably more "safe" to use domReady
, but in what context is it more safe than the other option? (I’m thinking stuff like document.write
and deferred scripts) We have used the BODY
way for nearly 5 years on many client sites, and we never run into any problems. It’s just a lot faster.
I’m also wondering, since there is so much fuzz about jsPerf and optimizing selectors for a couple of ms per 10000 executions, how come there is not much talk about this? It’s basically the first delay the user faces, and it seems to be fairly simple to slice 50-100 ms on each page load...