3

Exploring The Browser Fetch Priority API

 1 week ago
source link: https://blog.bitsrc.io/browser-fetch-priority-api-b4c55f905a84
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Exploring The Browser Fetch Priority API

Control What Loads First In Your Application!

1*8403wDMxqm11Z2lzQc6M2A.png

It’s important to have sites that load fast. One way to do this is to prioritize the resources that your web browser loads.

This is exactly what this article is all about. We’re going to be exploring the new — Fetch Priority API that lets you determine the priority of resources that are loading when your app loads for the first time.

When a browser loads a webpage, it assigns fetch priorities to resources like images, scripts, or CSS during the discovery and download process to optimize the order of resource retrieval. These priorities are influenced by the resource type and its location in the document.

What Are Priority Hints?

Priority Hints serve as a signal that lets developers specify the priority of resources (such as images, fonts, CSS, scripts, and iframes) for browsers as they initiate their loading process.

Sometimes the browser may lack clarity on the significance of a resource. Images typically load with low priority by default, assuming they are positioned below the visible portion or is tucked away in nested menus.

However, this default behavior may not align with the intention, especially when dealing with images crucial to the primary page content, which should ideally be loaded as soon as the user sees the site.

This is where priority hints come into play. Priority hints address this issue by providing the browser details regarding the significance of a resource.

One such way to achieve this in web development is using the fetchpriority attribute. This property lets you assign priorities to certain crucial images as high priority.

What Elements Support The Fetch Priority Attribute?

At the time of writing this article, the fetchpriority attributed is supported on the following elements:

  • script
  • iframe

The fetchpriority attribute can take on one of three values:

  • high: Designates the resource as high priority, requesting the browser to prioritize it unless its heuristics advise otherwise.
  • low: Marks the resource as low priority, instructing the browser to deprioritize it if its heuristics allow.
  • auto: The default value, indicating no specific preference, allowing the browser to autonomously determine the suitable priority.

For instance, suppose you intend to preload a background image on the page. By default, the image request will be initiated with a low priority. This is where the fetchpriority attribute comes into play to rectify the situation.

const img = new Image();
img.fetchPriority = "high";
img.src = "img/logo.png";

When we want to initiate an early fetch for a resource but also deprioritise it we can use as below.

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

fetch('https://example.com/', {priority: 'low'})
.then(data => {
// Trigger a low priority fetch
});
</script>

When we want to Employ Priority Hints in HTTP Link Preload Headers, we can use as below.

Link: </background.webp>; rel=preload; as=image; fetchpriority=high

When we want to use priority hints with the fetch API, we can use as below.

const req = new Request("/data.json",{ priority: "low"});

fetch(req)
.then(res => res.json)
.then(res => console.log("Response", res));

Note: I’ve used the priority flag to denote the priority of the request.

What is the Browser Compatibility of Fetch Priority?

1*slkLWCDwcHwHoJKXqAzXxw.png

Using The Fetch Priority On Chrome

Now that we have an understanding of Fetch Priority, let’s take a look at it in action and see how it performs on Google Chrome.

1*LGuaok2T_MrXKiBMJweZ0A.png
1*Tv-oc3hPSPQ1rjZNOO5i0w.png

I have done a small test using a sample website with LCP image and following are the test results I got. You can see the priority and the time taken to load the image in following captures.

In cases where priorities undergo modifications, utilize the "Big request rows" setting to observe both the initial and ultimate priority. The identical information is presented in a tooltip, irrespective of whether the "Big request rows" setting is enabled or not.

  • Without fetchpriority: The priority changes from Medium to High after the page renders for the first time.
1*JYpOZ8emFNMZihYhJh37yw.png
  • With low fetchpriority: Now the priority no longer changes and set to Low
1*klUxwf_D4haqRUu3lIx-8g.png
  • With high fetchpriority: Now the priority no longer changes, and the images are loaded immediately after the document request.
1*IHvDKhWUUO9StgubpeMNTw.png

What are the benefits of Fetch Priority?

Fetch Priority can be beneficial in several crucial aspects:

  • Elevate the priority of the Largest Contentful Paint (LCP) image by setting fetchpriority="high" on the image element, expediting the occurrence of LCP.
  • Enhance the priority of asynchronous scripts using improved semantics, surpassing the current workaround commonly employed (such as inserting a <link rel="preload"> for the async script).
  • Reduce the priority of scripts in the late body, facilitating improved sequencing with images.

When To Use Fetch Priority?

Understanding the browser's prioritization logic provides a few existing options to adjust the download sequence:

  • Arrange resource tags such as <script> and <link> based on the preferred download order. Resources with the same priority are typically loaded in the order of discovery.
  • Employ the preload resource hint to download essential resources sooner, especially those that the browser might not discover early on.
  • Utilize async or defer attributes to download scripts without impeding the loading of other resources.
  • Implement lazy-loading for below-the-fold content, allowing the browser to allocate bandwidth to more critical above-the-fold resources.

Tips for Implementing Fetch Priority

Fetch Priority can enhance performance in specific scenarios, as detailed earlier. Here are key considerations:

  • The fetchpriority attribute functions as a hint, not a directive. The browser aims to honor the developer's preference, but conflicts may lead to the browser applying its own resource priority preferences.
  • Fetch Priority and preload are distinct concepts. Preload is a mandatory fetch with default priority, aiding resource discoverability. In contrast, Fetch Priority is a hint for adjusting fetch priority without affecting discoverability.
  • The effects of a preload are more straightforward to observe and measure compared to Fetch Priority.
  • Fetch Priority can work alongside preloads, providing finer prioritization control. If a preload for an LCP image is specified early in the <head>, a high Fetch Priority may not yield significant gains. However, if the preload follows other resources, a high Fetch Priority can enhance the LCP. For critical images like CSS background images, consider preloading with fetchpriority="high".
  • While introducing Fetch Priority may not be feasible in the initial design, it serves as an optimization applicable later in the development cycle. Monitoring and adjusting priorities based on resource expectations can guide the implementation of Fetch Priority for further optimization.

Wrapping Up

Priority Hints serve as a valuable tool for signalling the priority of resources on your website, enabling a more strategic approach to load.

By using priority hints in your app, you’re able to gain 100% controllability of how your app resources are being loaded onto the browser.

Therefore, you’re able to significantly focus on improving the user experience by loading assets that’s important, first, and by delaying the loading of other assets in your app.

However, don’t over use Priority Hints, as an overzealous application may lead to diminishing returns and potential hindrance to overall performance rather than the intended speed improvements.

It's recommended to apply Priority Hints based on the specific needs and characteristics of your website.

Thank you for reading !


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK