- Preload, Prefetch And Priorities in Chrome
- Addy Osmani
- The Nuggets translation Project
- Translator: gy134340
- Proofread by: IridescentMia,vuuihc
Today we’ll delve into Chrome’s web protocol stack to give you a clearer picture of how early web loading (like ) works.
likeOther articlesAs described, preload is a declarative FETCH that forces the browser to request resources without blocking the documentonloadEvents.
Prefetch informs the browser that the resource may be needed in the future, but leaves the decision of whether and when to load the resource up to the browser.
Preload decouples the load event from the script parsing process. If you haven’t used it yet, check out Yoav Weiss’s article Preload: What Is It Good For? .
Success stories of Preload in production environments
Before we dive into the details, here’s a summary of the cases we found last year that used ProLoad and had a positive impact on loading:
Housing.com saw about a 10% reduction in interactionable time when switching scripts to Proload for their progressive Web applications.
Shopify achieved 50% (1.2s) text rendering optimization in Chrome Desktop after switching to Preload fonts, which completely solved their text flash problem.
Left: Using Preload, right: Not using Preload (video)
Use to load the font.
Treebo, one of the largest hotel sites in India, tested its desktop version over 3G, reducing the first screen rendering and interactivity latency by 1s each after using Preload for its top image and main Webpack package.
Similarly, Flipkart saved a lot of mainline idle time (on low performance phones over 3G networks) before routing resolution by using Preload for its progressive Web application’s main packaging file.
Above: preload not used, below: Preload used
Using Preload for scripts and CSS stylesheets, the Chrome data protection team saw an average 12% improvement in page first rendering time.
For Prefetch, it is widely used, and at Google we still use it to get key resources that speed up the rendering of search results pages.
Preload is used on many large sites, as you will see in the next article. Let’s take a closer look at how the network protocol stack actually treats Preload and Prefetch.
When should I use it< link rel = "preload" >
? When should I use it again< link rel = "prefetch" >
?
Suggestion: Use Preload for resources that are necessary for the current page and Prefetch for resources that may be used in future pages.
Preload is instructing the browser to pre-request resources (key scripts, fonts, main images) needed for the current page.
Prefetch is used in a slightly different context — resources that the user may use in other parts of the application, such as views or pages. If page A makes A prefetch request for page B, the resource fetching process and navigation request may be synchronized, whereas if we use preload, it will stop as soon as page A leaves.
With Preload and Prefetch, we have a solution for key resources for current and future page loading.
<link rel="preload">
和 <link rel="prefetch">
Cache behavior of
Chrome has four types of caches: HTTP caches, memory caches, Service Worker caches, and Push caches. Both preload and prefetch are stored in the HTTP cache.
When a resource is fetched by Preload or Prefetch, it can be moved from the HTTP cache to the renderer’s in-memory cache. If the resource can be cached (such as with valid cache-control and max-age), it is stored in the HTTP cache and can be used by present or future tasks. If the resource cannot be cached in the HTTP cache, it is instead stored in the in-memory cache until it is used.
What is Chrome’s network priority for Preload and Prefetch?
Here are the loading priorities of different resources in Chrome 46 and later in the Blink kernel (Pat Meenan)
Preloads use the “as” or “type” attribute to indicate the priority of the resource they request (for example, preloads using the “as=”style” attribute get the highest priority). Requests without the ‘as’ attribute are considered asynchronous requests, with’ Early ‘meaning requested before all image requests that have not been pre-loaded (and’ late ‘meaning after). Thanks Paul Irish for updating this table about developer tools and the priorities of various requests at the web layer.
Let’s talk a little bit about this chart.
Scripts get different priorities depending on whether they are asynchronous, delayed, or blocked in the file:
- Scripts where the network blocks before the first image resource are intermediate in network priority
- Scripts that block the network after the first image resource are low in network priority
- Asynchronous/delayed/inserted scripts (wherever they are) are low on the network priority list
Images (visible to the viewport) will be given higher priority (intermediate) than images (low) that are not visible to the viewport, so Chrome will try to load them lazily to some extent. Images with low priority will get a higher priority when they are discovered by the viewport after the layout is complete (note that images that are already in the layout will not have their priority changed).
Preload Resources loaded with the “as” attribute will get the same priority as the resource “type” attribute. For example, preload as=”style” will get a higher priority than as=” script “. These resources are also affected by content security policies (for example, scripts are affected by their “SRC” attribute).
Preloads without the “as” attribute will have the same priority as asynchronous requests.
If you want to know the priority attributes of various resources when loading, you can see them in the Developer tools Timeline/Performance area in the Network area:
In the Priority section under the Network panel
What happens when the page preload is already a resource in the Service Worker cache and HTTP cache?
It depends, but in general, it is a good case — if the resource has not exceeded the HTTP cache time or the Service Worker has not actively re-initiated the request, then the browser will not request the resource again.
If the resource is in the HTTP cache (Service Worker cache and network), preload will get a cache hit.
Will this waste users’ bandwidth?
** In both “preload” and “prefetch” cases, a portion of bandwidth may be wasted if the resource cannot be cached.
Preload resources that are not used will be warned in Chrome’s Console 3s after the onload event.
The reason is that you might use preload to cache certain resources to improve performance, but if you don’t use it, you’re doing nothing. On mobile, this amounts to a waste of user traffic, so make sure you preload objects.
What would cause a secondary fetch?
Preload and Prefetch are very simple tools that you can easily accidentally fetch twice.
Do not use “prefetch” as a backup for “preload”, they are applicable to different scenarios and often result in unanticipated secondary fetching. Use preload to fetch current tasks or use prefetch to fetch future tasks, not both.
Don’t expect preload and fetch() to work together, as this will result in a secondary download in Chrome. This is not unique to asynchronous requests. We have an open bug on this issue.
Use the “as” attribute for preload, otherwise it will not benefit from it.
If you use an explicit “as” attribute for a resource you preload, such as a script, you will cause a secondary fetch.
Preload fonts without Crossorigin will be retrieved twice! Make sure you add crossorigin to preload’s font, otherwise it will be downloaded twice. This request uses anonymous cross-domain mode. This recommendation also applies to font files under the same domain name, as well as other domain name retrieval (such as the default asynchronous retrieval).
Resources with intergrity attributes that cannot use the preload attribute (currently) also result in a secondary fetch. [integrity] (https://bugs.chromium.org/p/chromium/issues/detail?id=677022) attribute of the link element is not yet supported, currently has an open issue about it, This means that elements that exist integrity will discard preload resources. On the broad side, this can lead to repeated requests, and you need to make a trade-off between security and performance.
Finally, although it does not result in a secondary fetch, here are some suggestions:
Don’t preload everything! Instead, use preload to tell the browser about resources that could not have been discovered earlier so that it can retrieve them earlier.
Should I load all resource files in the header of the page? Any suggestions like limiting loading to 6 files?
This is a good example of tools rather than rules. The number of files you preload depends on network content, user bandwidth, and other network conditions while loading other resources.
For script files, the Preload key package is useful because it separates loading from execution. Script Async is bad because it blocks the window’s onload event. You can load images, styles, fonts, and media resources as soon as possible. Most of the time — and most importantly, you as the author have a clear idea of what the page needs right now.
Are there any magic attributes you need to know about prefetch? Of course,
In Chrome, if the user jumps from one page to the next, the prefetch request will continue without interruption.
In addition, Prefetch’s resource is cached in the network stack for at least 5 minutes, whether it is cacheable or not.
I’m using a custom “preload” in JS. How is it different from rel=”preload” or the preload header?
Preload decouples resource acquisition from execution, as in this case, preload is declared in the tag to be scanned by the Chrome Preload scanner. This means that, in many cases, preload gets retrieved (with its declared priority) before the HTML parser gets the tag. This will be much more powerful than custom Preload.
Wait, can’t I use HTTP/2 server push instead of preload?
Use push when you know the correct order in which resources are loaded, use the service worker to block resource requests that might require a second fetch, and use preload to speed up the start time of the first request — this works for all resource fetches.
Again, it all depends, but let’s imagine making a shopping cart in the Google Play store for a request to a shopping cart:
The main modules that load pages with Preload require the browser to wait for the play.google.com/cart payload so that the Preload scanner can detect dependencies, but this will then saturate the network pipes to make better requests for resources, which may not be optimal for a cold start, But it is very friendly for caching and subsequent requests for bandwidth.
With HTTP/2 server push, we can quickly saturate the network pipe when requesting play.google.com/cart, but we waste bandwidth if the resource is already in the HTTP or Service Worker cache. There is a trade-off between the two approaches.
While push is effective, it doesn’t fit all situations like Preload does.
Preload supports decoupling between download and execution. Thanks to its support for document onload events, we can now control the event after it has loaded. Getting JS packages to execute quickly at idle or getting CSS modules to execute at the correct point in time is very powerful.
Pushing content that cannot be used by third-party resources also effectively shortens the browser’s own resource priority situation by sending resources immediately. This should improve the performance of your application when you know exactly what you are doing, but you may lose some performance if it is not clear.
What is the preload HTTP header? How is it different from preload tags? How is it different from HTTP/2 server push?
Unlike other links, preload links can be placed in either HTML tags or HTTP headers. In each case, the browser directly loads the resource and caches it in memory. Indicates that the page has a high probability of using these resources and does not want to wait for the Preload scanner or parser to find it.
When the FINANCIAL Times used the Preload HTTP header on their website, they saved about 1s of display time for the opening image.
Below: Use preload, above: Use preload. Moto G4 test on 3G network.
Original: www.webpagetest.org/result/1703… After: www.webpagetest.org/result/1703… . You can use both forms of preload, but it’s important to know that according to the specification, many servers will initiate an HTTP/2 push when they encounter a Preload HTTP header. HTTP/2 push has a different performance impact than normal preload, so you want to make sure you don’t initiate unnecessary pushes.
You can use the preload tag instead of the preload header to avoid unnecessary push, or add a “nopush” attribute to your HTTP header.
How do I check link rel=preload support?
Check if is supported with the following code snippet:
const preloadSupported = (a)= > {
const link = document.createElement('link');
const relList = link.relList;
if(! relList || ! relList.supports)return false;
return relList.supports('preload');
};Copy the code
FilamentGroup also has a Preload detector as part of their asynchronous CSS loading library loadCSS.
Can you make preload’s CSS stylesheets work immediately?
Of course, preload supports tags based on asynchronous loading, and stylesheets using immediately apply the onload event to the document:
<link rel="preload" href="style.css" onload="this.rel=stylesheet">Copy the code
For more relevant examples, check out Yoav Weiss ‘great use example.
What are some broader applications of Preload?
According to the HTTPArchive,Many web sitesapplication< link rel = "preload" >
To load theThe font, including Teen Vogue and the others mentioned above:
otherSome sites like LifeHacker and JCPenny use FilamentGroup’sloadCSSTo load CSS asynchronously:
More and more progressive Web applications (such as Twitter.com mobile, Flipkart and Housing) use it to load the script required for the current link:
The basic idea is to keep it granular rather than monolithic, so any application can load dependencies or preload resources on demand and put them in the cache.
What is the current browser support for preload and prefetch?
According to CanIUse’s survey in Safari Tech Preview, has approximately 50% support and has approximately 70% support. is available to ~50% of the global population according to CanIUse and is implemented in the Safari Tech Preview. is available to 71% of global users.
More useful insights
- Yoav Weiss recently made changes to Preload CSS and blocking scripts in Chrome.
- He also recently divided Preload media into three different types: Video, Audio, and track.
- Domenic Denicola is seeking specification changes to support ES6 modules.
- Yoav Weiss also recently added HTTP header support for Link header support for “prefetch” resources to make it easier to load the next page.
Develop reading
- Preload — What is it good for? – Yoav Weiss
- A study by the Chrome Data Saver team
- Planning for Performance — Sam Saccone
- Webpack plugin for auto-wiring up
- What is preload, prefetch and preconnect? — KeyCDN
- Web Fonts preloaded by Zach Leat
- HTTP Caching: cache-control by Ilya Grigorik
Thanks to @Shopifyeng, @Adityapunjani, @Housingengg, @Adgad, @Wheresrhys and @__lakshya for sharing statistics.
Many thanks to the following technical reviewers and suggestions: Ilya Grigorik, Gray Norton, Yoav Weiss, Pat Meenan, Kenji Baheux, Surma, Sam Saccone, Charles Harrison, Paul Irish, Matt Gaunt, Dru Knox, Scott Jehl.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. Android, iOS, React, front end, back end, product, design, etc. Keep an eye on the Nuggets Translation project for more quality translations.