Prefetch, Preload and Preconnect

Prefetch, Preload and Preconnect

Resource hints, as the name suggests, are attributes in HTML that provide the browser with suggestions about how to handle or prioritise the loading of external resources such as scripts, stylesheets, fonts, images, and more to help browsers load web pages faster. They are used in scenarios where the page owners can anticipate what is supposed to happen in the future and which resources needs to be loaded and how optimising the overall performance. All the resource hints uses the 'rel' attribute in the <link> element.

There are three different types of resource hints: Prefetch, Preload and Preconnect.

  1. Prefetch

    Prefetch hints the browser to fetch and cache resources that might be needed for subsequent navigation, improving the loading time of future pages.

     <link rel="prefetch" href="/uploads/images/pic.png">
    

    There are two other types of prefetching techniques : DNS prefetching & Prerendering which we will discuss in subsequent blogs.

    Usecase: Consider a scenario for a news article web page where the user lands on the home page which has multiple links for different articles and when user clicks on the links, they land on to different pages. In this case, prefetching the resources (such as images, CSS, and JavaScript) required for the article pages while the user is on the homepage can reduce the loading time when they eventually navigate to those articles.

  2. Preload

    Preload hints the browser to fetch and cache a resource as soon as possible, even before it's needed. This is particularly useful for critical resources that are required for rendering the current page.

     <link rel="preload" href="/demo.js" as="script">
     <!--change as attribute to style, image, font, document, etc as per need-->
    
  3. Preconnect

    Preconnect hints the browser to establish early connections to third-party origins to reduce connection latency when resources from those origins are later requested. What it means is that it allows the browser to setup early connections before an HTTP request is actually sent to the server. This includes DNS lookups, TLS negotiations, TCP handshakes. This in turn eliminates roundtrip latency and saves time for users.

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

    Usecase: Consider a scenario where a website integrates with a third-party API to fetch data or a CDN to serve static assets such as images or JavaScript libraries. Preconnecting to these domains can significantly reduce the time required to establish connections when the browser needs to fetch resources from them.

These resource hints, when used judiciously, can help significantly improve the performance of the page by prefetching and loading the resources ahead of time, which can help improve user experience and interection.

Comment what are your thoughts on this?