What is link rel="preload"? How to Use It?

Jan 09 2024 by Oskay Günaçar

rel="preload" is an attribute used in <link> tags within HTML to instruct the browser to load certain resources early in the page load process. This is particularly useful for resources that are needed early by the browser but are not discovered until later during the parsing of HTML, such as fonts, scripts, and stylesheets.

What is The Syntax Of Preload (How to Use rel="preload")

The syntax for using preload in HTML involves the <link> tag within the <head> section of your HTML document. The basic structure is straightforward but allows for customization based on the type of resource being preloaded. Here's a breakdown of the syntax:

Basic Syntax

<link rel="preload" href="path/to/resource" as="type">

Components of the Syntax

  1. <link> Tag: This is the HTML element used for defining the relationship between the current document and an external resource.

  2. rel="preload": The rel (relationship) attribute specifies the type of relationship. In this case, preload indicates that the resource is to be preloaded.

  3. href="path/to/resource": The href attribute specifies the path to the resource you want to preload. This can be a relative or absolute URL.

  4. as="type": The as attribute is crucial because it defines the type of content being preloaded. This helps the browser to correctly prioritize the resource and apply the appropriate fetch policy. The value of as can vary depending on the resource type, such as script, style, font, image, media, document, or fetch.

Examples of Preload Syntax

  • Preloading a Stylesheet

    <link rel="preload" href="styles.css" as="style">

  • Preloading a JavaScript File

    <link rel="preload" href="script.js" as="script">

  • Preloading a Font

    <link rel="preload" href="font.woff2" as="font" crossorigin>

    Note: The crossorigin attribute is often necessary for fonts due to cross-origin policies.

  • Preloading an Image

    <link rel="preload" href="image.jpg" as="image">

Additional Attributes

  • crossorigin: Used primarily for fonts and fetch requests, this attribute is important for resources that require CORS (Cross-Origin Resource Sharing) handling.
  • type: To further specify the MIME type of the resource, the type attribute can be used, though it's optional.
  • media: For conditional loading, such as responsive designs, the media attribute can be used to specify the media query for which the resource is relevant.

What Types of Resources Can Be Preloaded with “link rel=preload”?

With the link rel="preload" attribute, a variety of resource types can be preloaded to improve web performance. Here's a list of common types of resources that are often preloaded:

1. Stylesheets (CSS)

  • Usage: <link rel="preload" href="style.css" as="style">
  • Purpose: Preloading CSS files can be particularly beneficial for critical CSS that styles content above the fold. It ensures that these styles are loaded early to prevent the Flash of Unstyled Content (FOUC).

2. JavaScript Files

  • Usage: <link rel="preload" href="script.js" as="script">
  • Purpose: For scripts that are crucial for the page or need to be executed as soon as possible, preloading can reduce the time to interactive.

3. Fonts

  • Usage: <link rel="preload" href="font.woff2" as="font" crossorigin>
  • Purpose: Preloading fonts is important for ensuring text is rendered with the correct font as soon as possible. The crossorigin attribute is often necessary for fonts due to the cross-origin nature of font files in many web projects.

4. Images

  • Usage: <link rel="preload" href="image.jpg" as="image">
  • Purpose: Preloading key images, especially those above the fold, can improve the perceived performance of a website. This is particularly useful for large hero images or critical background images.

5. Videos

  • Usage: <link rel="preload" href="video.mp4" as="video">
  • Purpose: For websites where a video is a key element (especially above the fold), preloading can ensure a faster start to video playback.

6. Audio Files

  • Usage: <link rel="preload" href="audio.mp3" as="audio">
  • Purpose: In cases where audio is an important part of the user experience (like a game or an interactive application), preloading can be beneficial.

7. Documents

  • Usage: <link rel="preload" href="document.pdf" as="document">
  • Purpose: If a document is central to the user's interaction with the page, preloading it can make accessing it faster and smoother.

8. Custom Fetch Requests (Fetch API)

  • Usage: <link rel="preload" href="data.json" as="fetch" crossorigin>
  • Purpose: This can be used for preloading dynamic data that will be fetched via the Fetch API, ensuring that the data is ready as soon as the JavaScript needs it.

How does Preloading Work?

Here's a detailed look at how preloading works:

1. Markup with rel=preload

  • Developers use the <link> tag in the HTML header with the rel="preload" attribute to specify resources that should be loaded early.
  • Syntax example: <link rel="preload" href="path/to/resource" as="type">
  • The as attribute is crucial as it specifies the type of content being preloaded (e.g., style, script, font, image, etc.). This helps the browser understand how to prioritize and handle the fetched resource.

2. Early Resource Fetching

  • When the browser parses the HTML and encounters a rel="preload" tag, it immediately starts fetching the specified resource.
  • This fetching happens in parallel with the browser's parsing of the rest of the HTML document.
  • This is particularly beneficial for resources that would otherwise be discovered late in the parsing process, like a stylesheet linked at the end of the document or a script file.

3. Priority and Resource Handling

  • Preloaded resources are typically given a high priority by the browser, ensuring they are loaded quickly.
  • The browser also respects the as attribute to correctly handle different types of resources. For instance, a preloaded font file is handled differently from a preloaded script in terms of CORS policy and how it is processed once downloaded.

4. Performance Improvement

  • Preloading can significantly reduce the time to first paint and time to interactive, as critical resources are loaded sooner.
  • It helps in rendering important content faster, improving the user experience, especially for content above the fold.

5. Caveats and Best Practices

  • Overuse Caution: Overusing preload can backfire. If too many resources are preloaded, it can lead to bandwidth contention and delayed processing of other critical resources.
  • Prioritization: It’s important to prioritize and preload only the most critical resources that are necessary for the initial rendering of the page.
  • Resource Management: Keep an eye on how these resources are managed after they are loaded, especially for resources like scripts and styles that may need to be applied or executed.

6. Browser Support

  • Modern browsers support rel="preload", but it's important to consider fallbacks or alternative strategies for browsers that do not support it.

In conclusion, preloading is a powerful tool in web performance optimization. It allows developers to guide the browser on what resources are important and should be loaded early, directly impacting the loading speed and rendering time of a webpage. However, like any optimization technique, it should be used judiciously and tested thoroughly across different scenarios and browsers.

Benefits of Using rel=preload

Using rel=preload in web development offers several benefits, particularly in terms of improving the performance and user experience of a website. Here are some of the key advantages:

1. Faster Page Load Times

  • Early Resource Loading: By preloading critical resources (like stylesheets, scripts, fonts, and images), these elements are available sooner to the browser, reducing the time it takes to render the page.
  • Parallel Loading: Preload allows resources to be downloaded in parallel with the HTML parsing process, making efficient use of the browser's resource loading capabilities.

2. Improved Rendering Performance

  • Reduced Render Blocking: Resources such as CSS and JavaScript can block the rendering of a page. Preloading these resources can minimize render-blocking time.
  • Optimized Critical Rendering Path: By prioritizing the loading of key resources, rel=preload helps optimize the critical rendering path, which is the sequence of steps the browser goes through to convert HTML, CSS, and JavaScript into pixels on the screen.

3. Enhanced User Experience

  • Faster Time to Interactive (TTI): Faster loading of essential resources means that interactive elements become functional more quickly, enhancing the user's experience.
  • Smooth Page Rendering: Ensuring that important resources are loaded early can prevent issues like FOUC (Flash of Unstyled Content) or delayed interactivity.

4. Control Over Resource Priority

  • Developer Control: Developers have more control over the order in which resources are loaded, allowing them to dictate which resources are most important for the initial load.

5. Efficient Use of Bandwidth

  • Resource Prioritization: By preloading key resources, the browser can make better use of available bandwidth, downloading important assets first.
  • Load Balancing: It can help balance the load on the network, as critical resources are fetched early and not all at once when the page is rendered.

6. Better Resource Management

  • Specifying Resource Types: The as attribute in rel="preload" ensures that the browser correctly prioritizes different types of content (like fonts, images, etc.) and applies the correct fetching policy.

7. Fallback Compatibility

  • Progressive Enhancement: While not all browsers support rel="preload", it can be used as a progressive enhancement. For browsers that do support it, they benefit from the improved loading performance, while browsers that don’t will still load the page normally.

8. SEO Advantages

  • Faster Load Times and Better User Experience: These factors can contribute positively to search engine ranking, as search engines like Google prioritize fast-loading and user-friendly websites.

Best Practices and Considerations For Preload

When implementing link rel="preload", adhering to best practices and considering certain factors is crucial to maximize its effectiveness without causing unintended side effects. Here are some detailed insights and considerations:

Selecting Resources for Preloading

Choosing the right resources to preload is essential. Focus on critical assets that impact the first paint or first meaningful paint of your page. These typically include stylesheets, scripts required for initial render, key images, and web fonts. It's important to analyze your page's load performance to identify which resources are delaying the critical rendering path.

Using the as Attribute Properly

The as attribute in the preload link tag is crucial because it informs the browser about the type of content being preloaded. This ensures that the browser requests the resource with the correct headers and prioritizes its loading appropriately. For instance, preloading a font file without the as="font" attribute can lead to incorrect prioritization and misuse of the preload feature.

Balancing the Number of Preloaded Resources

While preloading can accelerate loading times, overdoing it can have the opposite effect. Each preloaded resource consumes bandwidth and browser resources. If too many resources are preloaded, it could lead to resource contention, negatively impacting the performance. Balance is key; prioritize only the most critical resources for preloading.

Considering Browser Support and Fallbacks

Not all browsers support the preload feature. Therefore, it's important to implement it as a progressive enhancement. For browsers that don't support preload, ensure that your website still loads correctly, albeit potentially less optimally. This approach ensures a consistent user experience across all browsers.

Handling Cross-Origin Requests

When preloading resources from different origins, CORS (Cross-Origin Resource Sharing) settings must be considered. For certain types of resources like fonts, failing to correctly handle CORS can lead to the resource not being used, negating the benefits of preloading. Ensure that your server is configured to serve these resources with the appropriate CORS headers.

Monitoring Performance Impact

After implementing preload, continuously monitor its impact on performance. Tools like Google's Lighthouse or Chrome DevTools can be invaluable in assessing whether your preload strategy is effective or if adjustments are necessary. Look for metrics like Time to First Paint (TTFP) and Time to Interactive (TTI) to gauge performance improvements.

Updating Preload Strategy Over Time

A website's resource profile can change over time as content gets updated. Regularly review and update your preload strategy to ensure it aligns with the current set of critical resources. This ongoing optimization ensures that preload continues to positively impact performance as your website evolves.

What Are The Other Browser Hints Besides Preload?

Besides preload, there are several other browser hints that developers can use to optimize the performance of their websites. These hints provide instructions to the browser about how to handle resources, allowing for more efficient loading, parsing, and rendering. Understanding these additional browser hints is key to implementing a comprehensive web performance strategy:

Preconnect

  • Purpose: preconnect allows the browser to set up early connections before an HTTP request is actually made. It can perform DNS lookups, TLS negotiations, and TCP handshakes in advance, saving time when the request is actually made.
  • Usage: <link rel="preconnect" href="https://example-domain.com">

Prefetch

  • Purpose: prefetch is used to instruct the browser to fetch resources that will be needed in the near future (e.g., for the next navigation or page load). This is different from preload, which focuses on resources for the current page.
  • Usage: <link rel="prefetch" href="path/to/next-page-resource">

Prerender

  • Purpose: prerender tells the browser to load an entire webpage in the background, including all its resources. This can be useful for loading a page that the user is highly likely to visit next.
  • Usage: <link rel="prerender" href="url-to-next-page">

Dns-prefetch

  • Purpose: dns-prefetch is used to resolve domain names before a user clicks on a link. This reduces DNS lookup times for external resources and sites.
  • Usage: <link rel="dns-prefetch" href="//example-domain.com">

Lazy Loading

  • Not a Link Hint, But Related: Although not a link relation, lazy loading is another performance optimization technique. It delays the loading of non-critical resources (like images and iframes) until they are needed (e.g., when they're about to enter the viewport).
  • Usage: <img src="path/to/image" loading="lazy"> for images and iframes.

Which Metrics Can Be Improved With Preload?

Implementing preload in web development can positively impact various performance metrics. These metrics are key indicators of how efficiently and quickly a website's content is delivered and rendered to the user. Understanding the impact of preload on these metrics helps in fine-tuning website performance and enhancing user experience.

Impact on Time to First Byte (TTFB)

Time to First Byte (TTFB) measures the time from the start of a page request to when the first byte of a response is received. While preload doesn't directly affect TTFB since it deals more with how a server processes a request, efficient use of preload can ensure that once the TTFB phase is complete, the subsequent resources are loaded more quickly. This is particularly beneficial for resources that are essential for rendering the initial view of the page but are typically discovered late in the page load process.

Reduction in First Contentful Paint (FCP)

First Contentful Paint (FCP) marks the time at which the first text or image is painted on the screen. preload can have a substantial impact on this metric. By preloading key resources like CSS and fonts, the browser can render content to the screen much faster. This is especially noticeable for resources that block the rendering path, such as custom fonts or stylesheets that dictate the layout and look of the above-the-fold content.

Improvement in Largest Contentful Paint (LCP)

Largest Contentful Paint (LCP) measures when the largest content element in the viewport becomes visible. This could be a large image, a block of text, or a video. Using preload to fetch large content files like high-resolution images or video files can significantly improve LCP. By ensuring these large files start loading earlier in the page load process, they become visible sooner, enhancing the perceived load speed of the site.

Enhancement of Speed Index

Speed Index measures how quickly the contents of a page are visibly populated. preload can improve this metric by prioritizing the early loading of critical resources that contribute to the visual completeness of the page. A faster Speed Index implies a better user perception of the page loading process, as more of the page content appears to load quickly.

Reduction in Time to Interactive (TTI)

Time to Interactive (TTI) is the time it takes for a page to become fully interactive. Preloading important JavaScript files can reduce TTI. If scripts that are essential for user interaction are loaded earlier, the page becomes interactive more quickly. This is crucial for web applications where interactivity is a key component of the user experience.

Impact on Total Blocking Time (TBT)

Total Blocking Time (TBT) measures the total amount of time between FCP and TTI where the main thread was blocked, preventing user input. By preloading crucial blocking resources, the time during which the browser is busy parsing and executing scripts or styles can be reduced, thus lowering the TBT and making the page more responsive to user input sooner.

Conclusion

In conclusion, the use of `rel="preload"` in web development emerges as a potent tool for enhancing website performance across multiple dimensions. By strategically preloading critical resources such as stylesheets, JavaScript files, fonts, images, videos, audio files, documents, and data for fetch requests, developers can significantly improve key website performance metrics. This approach leads to faster page load times, reduced render blocking, and enhanced user experience with smoother page rendering and quicker interactivity. 

The implementation of `preload` also grants developers greater control over resource priority and aids in the efficient use of bandwidth. When applied carefully, keeping in mind browser support and best practices, `preload` can contribute to an improved Speed Index, reduced Time to Interactive (TTI), and a lower Total Blocking Time (TBT), thereby offering a more responsive and user-friendly experience. 

However, it's crucial to balance the use of `preload` to avoid overloading the browser with too many preloaded resources, which can be counterproductive. Regularly monitoring performance impact and adjusting the strategy according to the evolving content of the website ensures that the benefits of preloading are continually realized. 

In addition to `preload`, other browser hints like `preconnect`, `prefetch`, `prerender`, `dns-prefetch`, and lazy loading techniques play a pivotal role in optimizing web performance. Each of these techniques, used in the right context, can contribute to a more efficient and seamless web experience, reinforcing the importance of a well-rounded approach to resource management in web development.

Oskay Günaçar
Oskay Günaçar is a Technical SEO expert and backend developer. His main areas of interest are back-end programming, Python, Django, Go, semantic SEO, technical SEO. With more than 5 years of SEO experience, he has held SEO specialist positions at İkiler, Webtures, Boosmart, and Storyly.io companies, and has been involved in numerous projects as an outsourced expert. Through the TechSEOHub website, he aims to share the expertise and experience he has gained from managing and developing (SEO) processes for many successful and large websites in the industry, and to produce content for easy access to accurate and high-quality information.