Friday, August 14, 2009

Prefetching files using jQuery

Since years, Gecko-based browsers have supported link prefetching, while other browsers (notably Internet Explorer) are lacking this function.

Here's a simple JavaScript-based work-around based on jQuery:
$(document).ready(function() {

// Prefetch all files referenced in [LINK rel="prefetch" href="xyz"] tags...
var $prefetchTags = $('HEAD LINK[rel=prefetch][href]');

// ...starting with the ones that can be done asynchronously via AJAX...
.each(function() {
$.ajax({url: this.href, dataType: 'text'});

// ...followed by all referenced images,
.each(function() {
new Image().src = this.href;
It looks for all LINK tags in the HEAD section of the HTML document that have rel="prefetch" set.

Then it processes all HREF attributes, but treating text files and images differently, since text files can easily be downloaded using asynchronous HTTP requests (a.k.a. XMLHttpRequest or AJAX), while this method is not well-suited for fetching binary files.

This approach may be a bit rough on the edges, since I've only done limited testing, on Fireefox 3.0/Mac and MSIE 8.0/WinXP.

No comments:

Post a Comment