RSS

Prefetching Files Using jQuery

14 Aug

>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...
$prefetchTags.filter('[href$=.txt],[href$=.js],[href$=.html]')
.each(function() {
$.ajax({url: this.href, dataType: 'text'});
});

// ...followed by all referenced images,
$prefetchTags.filter('[href$=.png],[href$=.jpg],[href$=.jpeg],[href$=.gif]')
.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.

Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: