Faster load times is one of the major goals of every web dev team . Faster initial loads and low First Contentfull Paint have been proven to increase user conversions and provide better user experience .
If you have proper insights about the average user navigation through your app. We can then improve the performance by prefetching the resources the user might need next . Like on a checkout page while the user is filling address data we can pefetch and cache the resources for payment page .
What is Link Prefetching
Link prefetching is a browser mechanism , which utilizes browser idle time to download or prefetch documents or resources that the user might visit in near future .
Prefetch Resources using Html link element .
To prefetch resources browser looks for an HTML link tag with a prefetch relation. like :
<link rel="prefetch" href="/images/future-image.png">
The browser looks for these hints and puts all these resources in a queue to be downloaded in idle time and stored in prefetch cache . And when the user will request for the resource in future the browser will directly serve it from the cache .
You can also use the http LINK header with prefetch relation to achieve the same
Link: </images/futere.jpeg>; rel=prefetch
What resources can be Prefetched .
You can use link prefetching to either prefetch resources like Javasript, images , css , etc like :
<link rel="prefetch" href="/js/stripe.js" as="script"> <link rel="prefetch" href="/css/emoji.css" as="stylesheet">
Or you can even prefetch whole pages , that you think the user might definetly visit .
<link rel="prefetch" href="/future-page" as="document">
Prefetching with webpack
If you are using webpack as the bundler for your app . You can utilize the magic comments to tell webpack to prefetch some resources .
import(/* webpackPrefetch: true */ 'lodash.sortby') .then(module => module.default)
webpack will now automatically generate prefetch link for lodash.sortby .
Few things to keep in mind ..
Prefetching does not work with anchor tags . prefetching is not supported by firefox version below 3.4
Never prefetch resources mindlessly . If the user doesn’t need it . It will cost the user bandwidth and money .
Only prefetch resources that you are certain of or have high changes of being used in future