Mind that age! This blog post is 6 years old! Most likely, its content is outdated. Especially if it's technical.

I just rolled out a change here on my personal blog which I hope will make my few visitors happy.

Basically; when you hover over a link (local link) long enough it prefetches it (with AJAX) so that if you do click it's hopefully already cached in your browser.

If you hover over a link and almost instantly hover out it cancels the prefetching. The assumption here is that if you deliberately put your mouse cursor over a link and proceed to click on it you want to go there. Because your hand is relatively slow I'm using the opportunity to prefetch it even before you have clicked. Some hands are quicker than others so it's not going to help for the really quick clickers.

What I also had to do was set a Cache-Control header of 1 hour on every page so that the browser can learn to cache it.

The effect is that when you do finally click the link, by the time your browser loads it and changes the rendered output it'll hopefully be able to do render it from its cache and thus it becomes visually ready faster.

Let's try to demonstrate this with this horrible animated gif:

(or download the screencast.mov file)



1. Hover over a link (in this case the "Now I have a Gmail account" from 2004)

2. Notice how the Network panel preloads it

3. Click it after a slight human delay

4. Notice that when the clicked page is loaded, its served from the browser cache

5. Profit!

So the code that does is is quite simply:

$ ( function () { var prefetched = []; var prefetch_timer = null ; $ ( 'div.navbar, div.content' ). on ( 'mouseover' , 'a' , function ( e ) { var value = e . target . attributes . href . value ; if ( value . indexOf ( '/' ) === 0 ) { if ( prefetched . indexOf ( value ) === - 1 ) { if ( prefetch_timer ) { clearTimeout ( prefetch_timer ); } prefetch_timer = setTimeout ( function () { $ . get ( value , function () { // necessary for $.ajax to start the request :( }); prefetched . push ( value ); }, 200 ); } } }). on ( 'mouseout' , 'a' , function ( e ) { if ( prefetch_timer ) { clearTimeout ( prefetch_timer ); } }); });

Also, available on GitHub.

I'm excited about this change because of a couple of reasons:

On mobile, where you might be on a non-wifi data connection you don't want this. There you don't have the mouse event onmouseover triggering. So people on such devices don't "suffer" from this optimization. It only downloads the HTML which is quite light compared to static assets such as pictures but it warms up the server-side cache if needs be. It's much more targetted than a general prefetch meta header. Most likely content will appear rendered to your eyes faster.

Related posts