Prerender on hover?

Avatar of Chris Coyier
Chris Coyier on

InstantClick is a pretty popular JavaScript library (4,344 stars, as I type). This is the gist:

Before visitors click on a link, they hover over that link. Between these two events, 200 ms to 300 ms usually pass by (test yourself here). InstantClick makes use of that time to preload the page, so that the page is already there when you click.

You hover a link, it Ajaxs for that page and prerenders it. On click, it replaces the <body> and <title> and changes the URL.

I just heard about it. Seems pretty smart. Progressive enhancement. Increased perceived performance. I can imagine one objection being bandwidth concerns. Downloading every page I hover over seems a bit bandwidth greedy.

It got me thinking though… isn’t there a newfangled prerendering thing? There is:

<link rel="prerender" href="(url)">

It’s not that newfangled, actually. Steve Souders wrote about it in 2013:

This is like opening the URL in a hidden tab – all the resources are downloaded, the DOM is created, the page is laid out, the CSS is applied, the JavaScript is executed, etc. If the user navigates to the specified href, then the hidden page is swapped into view making it appear to load instantly.

Can I Use shows decent support:

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

ChromeFirefoxIEEdgeSafari
13No1179No

Mobile / Tablet

Android ChromeAndroid FirefoxAndroidiOS Safari
123NoNoNo

Doesn’t that mean we could do something like this?

var links = document.querySelectorAll('a');

[].forEach.call(links, function(link) {
    
  link.addEventListener("mouseenter", function() {
    
    var newPreLoadLink = document.createElement("link");
    newPreLoadLink.rel = "prerender";
    newPreLoadLink.href = link.href;
    
    document.head.appendChild(newPreLoadLink);
    
  })
  
});

The question is if dynamically-inserted link elements like that actually trigger the prerendering. I did a fairly primitive test in Chrome, and it didn’t seem to work. Oh well.

If you wanted to be even more predictive than hover, you could try Premonish, “A library for predicting what element a user will interact with next.”

If you’re interested in this kind of thing, prerendering isn’t the only kid on the block. Robin wrote about it all last year.