Friday, March 13, 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" });

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.


  1. Hey :)

    Nice, I should learn jQuery some day.

    Btw, that's another good web-performance talk, ~50mins long:

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

  3. This comment has been removed by a blog administrator.

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

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

  6. I was writing a slide-show type page where I wanted at least 2 seconds between the image loading and the next image (so that pictures taking a long time to load didn't get a shorter view time), so I adapted your method like this:

    $.ajax({ url: pics[i].src, cache:true, success: function() {
    $('#image').attr('src', pics[i].src);
    setTimeout(next, time);

    Worked like a charm :-)