Leveraging perceived performance using Prefetch and Prerender

<tl;dr> Check out prefetch/pre-render on Codepen </tl;dr>

As developers, we’re constantly trying to make our products perform well. We’ll make your stuff look good, but also aim to make it as fast as possible. Because hey, people don’t like to wait around until your slow clunky page has loaded. Sounds familiar right? That’s the reason we do caching, minifying, image compressing and use CDN services.

Some optimizations however don’t necessarily speed up your site, but improve the overall experience of the user while browsing through pages on your website. A while ago I read an excellent article about link prefetching and pre-rendering content. This HTML5 native technique basically allows you to load content to be used later while the browser is idle. This can be anything, from a JS resource needed in a following page, up to a complete webpage. This results in this prefetched content being almost instantly displayed when needed.

It’s as simple as placing this inside the <head>:

<link rel="prefetch" href="http://www.zwaarcontrast.nl">

Or to render a complete page in advance:

<link rel="prerender" href="http://www.zwaarcontrast.nl">

Support for the prefetch feature is actually pretty good, only Apple’s Safari isn’t onboard. (And Opera Mini, but does that browser actually support anything?) Pre-render is currently supported by Chrome, Opera and Edge. It’s worth noting pre-rendering will not work for https pages.

And now for the coolest part; the tags can be inserted through Javascript at runtime! What a time to be alive! After we predict a user is likely to click on a link, we can preload/pre-render that page. The result is almost instant loading when the link is actually pressed. One could think of the next page in a series of articles or the next page on an archive or search results page. On a personal note I think this is the best way to use this technique, because we load stuff that will actually be used, and not just eat the bandwidth of an unsuspecting audience. This is very important to keep in mind while implementing stuff like this; will the end user actually benefit from it?

I implemented this feature as a test case in my pet project Katwijk in Oorlog. On the bottom of every article page you will find a link to the next article. When the link almost scrolls into view, the page will be prefetched. You’ll benefit from pre-render if you’re on Chrome or Edge. I chose to implement pre-render and prefetch because the link at the bottom of the page is very likely to be clicked, as it’s the only prominent link at that part of the page. Navigating to the next article will feel almost instant. A slightly adapted version of the code used in this testcase can be found in this Codepen.

Further reading

<tl;dr> Check out prefetch/pre-render on Codepen </tl;dr>