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" });
})(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.

7 comments:

spacer
Oren said...

Hey :)

Nice, I should learn jQuery some day.

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

spacer
orip said...

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

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

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

spacer
tinamaria said...

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

spacer
Viktor Lofgren said...

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 :-)

spacer
Ryan Donovan III said...

I'm into internet marketing in long island and in this kind of business jQuery plays a big part cause it attracts web visitors because of its dynamics. It also has a wide array of functions that makes web developers more flexible when it comes to modifying a website.

Newer Post Older Post Home
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.