Sunday, December 15, 2019

Faster Websites in 60 Seconds with preload and prefetch

Are efficient developers lazy or are lazy developers efficient? Ask this open ended question at your next interview and you will have an interesting conversation. While the goal is to improve performance, if we can do it in a lazy fashion (60 seconds or less) it's a win-win! This performance tip is rarely applied in our industry and we're all missing out! According to the 2019 State of the Web Report, only 14% of desktop site are using preload and about 1% are using prefetch.

preload

Preloading assets tells the browser to load critical assets earlier in the page loading lifecycle and as a result improves page load performance. Critical assets are the resources (JavaScript, CSS, images, fonts, etc) that are required to render the initial page or the displayable screen above the fold. For examples of preloading assets refer to Listing 1. It's very important to include the as attribute when preloading assets because it sets the content-type header, accept header, loading priority, and helps cache the asset for future requests. A complete listing of the content types that can be preloaded are listed here.


// Without preloading
<link rel="stylesheet" href="fancybox.css">
<script src="fancybox.js"></script>

// With preloading
<link rel="preload" href="preloaded-image.jpg" as="image">
<link rel="preload" href="fancybox.css" as="style">
<link rel="preload" href="fancybox.js" as="script">
Listing 1. Preload critical assets

prefetch

Prefetching assets tells the browser to load these non-critical assets in the background after the page loading lifecycle has completed. As a result, these assets will be cached for future page navigations which greatly improves page load performance. For examples of prefetching assets refer to Listing 2.


// Without prefetching
<link rel="stylesheet" href="fancybox.css">
<script src="fancybox.js"></script>

// With prefetching
<link rel="prefetch" href="preloaded-image.jpg" as="image">
<link rel="prefetch" href="fancybox.css" as="style">
<link rel="prefetch" href="fancybox.js" as="script">
Listing 2. Prefetch non-critical assets

Auditing Performance

How much can your site gain by preloading and prefetching assets? Find out using Lighthouse in Chrome's Dev Tools (see Figure 2). Check the "Performance" option and run the audit. Then refer to your estimated savings report to see your performance improvement opportunity (see Figure 3). A faster site will also boost your SEO score so this lazy technique has an additional benefit of boosting revenue!


Figure 2. Chrome's Performance Audit via Lighthouse

Figure 3. Performance savings report by preloading and prefetching

No comments :

Post a Comment