Web Performance Improvement: The Client Side Of The Equation
We've looked at a lot of server-side tricks to reduce the page load and improve users' experience when accessing our content. Now we'll look at client-side client hints and tools to optimize our content. ## Client side resource hints The basic way to preload a resource is to use the `` element with three attributes: - `rel` tells the browser the relationship between the current page and the resourced linked to - `href` gives the location of the resource to preload - `as` specifies the type of content being loaded. This is necessary for content prioritization, request matching, application of correct content security policy, and setting of the correct Accept request header. ```html ``` ### Early loading fonts and the crossorigin attribute Loading fonts is just the same as preloading other types of resources with some additional constraints ```html ``` You must add a crossorigin attribute when fetching fonts since they are fetched using anonymous mode CORS. Yes, even if your fonts are of the same origin as the page. The type attribute is there to make sure that this resource will only get preloaded on browsers that support that file type. Only Chrome supports preload and it also supports WOFF2, but not all browsers that will support preload in the future may support the specific font type. The same is true for any resource type you’re preloading and which browser support isn’t ubiquitous. ### Responsive Loading Links Preload links have a media attribute that we can use to conditionally load resources based on a media query condition. What’s the use case? Let’s say your site’s large viewport uses an interactive map, but you only show a static map for the smaller viewports. You want to load only one of those resources. The only way to do that would be to load them dynamically using Javascript. If you use a script to do this you hide those resources from the preloader, and they may be loaded later than necessary, which can impact your users’ visual experience, and negatively impact your SpeedIndex score. Fortunately, you can use preload to load them ahead of time, and use its media attribute so that only the required script will be preloaded: ```html ``` ### Resource Hints In addition to preload and server push, we can also ask the browser to help by providing hints and instructions on how to interact with resources. For this section, we’ll discuss - DNS Prefetching - Preconnect - Prefetch - Prerender #### DNS prefetch This hint tells the browser that we’ll need assets from a domain so it should resolve the DNS for that domain as quickly as possible. If we know we’ll need assets from example.com we can write the following in the head of the document: ```html ``` Then, when we request a file from it, we’ll no longer have to wait for the DNS lookup. This is particularly useful if we’re using code from third parties or resources from social networks where we might be loading a widget from a `