Preload, Prefetch, and Preconnect

09 December, 2017

Working on a Polymer project recently, I got to experiment with serving the content from Firebase Hosting, which now offers support for HTTP/2 and Server Push. Server Push allows content to be delivered speculatively: content is delivered whether or not the user has it already, and in some cases it might not be required at all.

Preload

To take advantage of this ability though, I needed to declare the assets I wanted to be pushed down. In my firebase.json file I declared:

If you inspect this site, you'll see that Gatsby does this for me in production. Coupled with HTTP/2 on Cloudfront, visitors should experience a fairly snappy load. Essentially, all assets for a page are transferred in a single round trip, though it does mean if you're a repeat visitor (hi mum!), I'm probably using bandwidth unneccessarily. Addy Osmani suggests that:

Use Push when you know the precise loading order for resources and have a service worker to intercept requests that would cause cached resources to be pushed again.

Prefetch

<link rel="prefetch" href="/font.woff2">

Prefetch is another resource hint developers can take advantage of. Prefetch tells the browser that a resource will be needed on the next page, or navigation. Resources marked as such will be treated as a much lower-priority fetch than those with preload, and it's up to the browser to make the call as to whether it will load it or not. I've seen a pattern where a webfont is set to be pre-fetched so that it doesn't block rendering on the first load, but is available right away when a visitor navigates to a new page.

All of these techniques can be used in an attempt to improve the performance of your site but it's a trade-off between second-guessing the behaviour of your guests, while not exhausting their bandwidth unneccessarily – especially for those on metered connections.