Normally web folks suggest loading Javascript at the bottom of the page, but with something like jQuery it's quite handy to be able to use stuff like $(function() { $('#node').show(); }
inline in your pages. It also seems like jQuery ends up being the biggest/slowest critical component on many pages, so waiting for the page to load to doing something often really means waiting for jQuery to load to do something.
So I wrote a small script that performs a tiny, tiny piece of jQuery functionality but allows you to happily load jQuery at the bottom of the page. In my tests it doesn't seem to have any impact on the time deferred stuff takes to fire, but it reduces time taken to display content by at least 200ms. It's not totally beautiful but it's alright. And it wouldn't be that hard I think to emulate all the traditional jQuery ways of deferring execution, so you wouldn't have to change any existing code.
<script>
var $_={
_callbacks:new Array,
ready:function(a){this._callbacks.push(a)},
runDeferred:function(){jQuery.each(this._callbacks,function(a,b){b.call(document,jQuery)})}
}
var $=function(a){$_.ready(a)};
$(function($) {
$('#elem').hide();
});
</script>
<body>
Page content
...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script> jQuery(function() { $_.runDeferred() }); // At this point our temporary $() is gone anyway </script>
</body>
This is a simple alternative. You get a simple mechanism for including deferred behaviour inline. It will execute just as fast as it would with regular jQuery call. And you'll save around 200ms on each page load and frequently more. Or at least your content will show up faster. Even when jQuery is totally cached and there's no network operations at all, on my old system it looks like just running the 233kb of uncompressed Javascript that is jQuery 1.6.4 takes about 180ms. That's a delay for content displaying content that really doesn't seem necessary, since while the content is loading you're rarely using jQuery for anything more than deferred behaviour handling.
Recently on a set of forms I’ve been putting this at the top of the page –
$(document).ready(function(){
var x = {
// Query function
};
}
$(“#…”).autocomplete(x);
Does that not do the same thing? – ie wait until the page has loaded?
andrew / 5:51pm / 25 September 2011
The point is that you don’t have to load jQuery at the top of the page. Javascripts block loading and display in most browsers and even when the page is 100% cached it still takes 50-100ms just to “compile” the current version of jQuery. The only real benefit of having these delays are that you can use $(document).ready() all through your page. That’s kind of convenient, but you don’t need to load that enormous library just to get a document ready function.
Ryan / 6:44pm / 20 October 2011
That’s really clever.
Laurence / 8:00pm / 5 November 2011