Saturday 20 January 2018

Lazy loading stylesheets - resource hints

One thing I forgot to mention in my previous post on lazy loading stylesheets using loadCSS, was how you can improve performance even further by tipping the browser off to what you're going to lazy load in advance.  This is called using resource hints.

There are a few different levels of hint that you can use, so I'll go through them individually, before giving the example that I've used.


DNS Prefetch

This tells the browser that there will be a file required from this domain, and that it should get a head start by doing the DNS lookup (converting the domain name into an IP address).

For example...
<link rel="dns-prefetch" href="https://example.com">
Preconnect

This tells the browser to go a step further and make the TCP handshake - this is required at the start of each TCP connection.  It will also do the TLS negotiation, if the link points to an https: resource - this is where the browser and the server decide what type of encryption they both understand.

For example...
<link rel="preconnect" href="https://example.com">

Prefetch

This is used to download and cache a particular resource, so can be used if you're sure a particular asset will be required later.  The file is downloaded as relatively low priority, but will still give the browser a head start - this is often used for fetching files for the next anticipated page or future interaction on the current page.

For example...

<link rel="prefetch" href="https://example.com/style.css">

Subresource

This is similar to prefetch, in the sense that it is used to download and cache a particular resource.  However, the file is downloaded as a high priority, meaning it is best used when requesting files for the current page.  Having said that, this has been superceded by "preload" and has been removed from Chrome.


So for me, I typically like preconnect.  In my example from my lazy loading stylesheets using loadCSS post, I was lazy loading a Google Font stylesheet.  In this case, there are two domains I want to preconnect to, which can be done like this...
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com">
The first is the location of the stylesheet itself, and the second is the location of the font file that will subsequently be downloaded.  I could use prefetch on the stylesheet file itself, if I wanted to, but this returns dynamic content based on your browser, so it would be impossible to prefetch the web font file itself.

No comments:

Post a Comment