Thursday, March 12, 2009

Prefetching JavaScript (or anything) with jQuery

While users are logging into a web site, I thought why not prefetch some JavaScript files they'll be needing on the next page?

I could load them with Ajax and this will be invisible to users (see the Even Faster Web Sites talk by Steven Souders, and his discussion of browser busy indicators).

The following seems to work, prefetching 2 files in parallel:

(function($) {
 $.ajax({ url:"/js/file1.js", cache:true, dataType:"text" });
 $.ajax({ url:"/js/file2.js", cache:true, dataType:"text" });
})(jQuery);

The 'text' dataType means jQuery won't try to evaluate the JavaScript it fetches. The 'cache' parameter defaults to 'true', but I prefer adding it.

I tested several browsers with a proxy, and the JavaScript files are cached - cool! I presume this technique would work with any resource, not just JS.

submit to reddit Submit Story to Digg

5 comments:

Oren said...

Hey :)

Nice, I should learn jQuery some day.

Btw, that's another good web-performance talk, ~50mins long: http://yuiblog.com/blog/2007/08/29/video-smarr/

orip said...

Hi Oren!
Thanks for the link, looks very interesting.

ooblogger said...
This post has been removed by a blog administrator.
Joe McCann said...

Just wrote a jQuery method today to preload all images in a directory....works like a charm.

tinamaria said...

I have already learnt different Queries but, now i have learnt jquery through this post.
nice sharing.