Translator: Front-end wisdom

Original text: medium.com/reloading/p…

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

Today, we’ll delve into Chrome’s Web stack to figure out how web loading primitives like < Link rel= preload > & < Link rel= prefetch > work so you can use them more effectively.

To read more quality articles pleaseJabber at the GitHub blog, a hundred quality articles a year waiting for you!

As noted in other articles, preload is a declarative FETCH that forces the browser to request a resource without blocking the Document’s onload event.

Prefetch tells the browser that the resource may be needed in the future, but it is up to the browser to decide when to load the resource.

The network request starts here before it is perloaded, after which it moves from left to right as it parses

Some examples of using perload

Before getting into the details of perload, let’s take a look at some examples of its use.

Housing.com saw about a 10% reduction in interactionable time when switching scripts to Proload for their progressive Web applications.

After Shopify used Preload to load Web fonts, Chrome Desktop) improved text rendering time (1.2 seconds) by 50%, which completely solved their text flash problem.

Left: Use preload. Right: do not use preload

use< link rel = "preload" >Load the fonts

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: Not usedproloadLoad, below: usepreloadloading

The Chrome data protection team found an average 12% improvement in page first rendering time for pages that can use Preload on scripts and CSS stylesheets.

Prefetch is widely used, and at Google we still use it to prefetch some of the key resources that speed up the rendering of search results pages.

Preload is well used on large sites, and you can find out more about these security features later in this article. Before we do that, let’s take a closer look at how the network stack actually handles prefetch versus prefetch.

When to use and?

Tip: Preload usually loads resources that are required by the current page, while prefetch usually loads resources that may be used by other pages.

Preload tells the browser to pre-request resources (key scripts, fonts, main images, etc.) needed for the current page.

Prefetch is used in a slightly different scenario — the user may jump to resources needed by other pages in the future. 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.

Between Preload and Prefetch, we have a solution to the problem of the main resources required for the current page or the page to jump to.

And cache behavior

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 preloaded or prefetch, it is transferred from the network stack to the HTTP cache and into the renderer’s memory cache. If the resource can be cached (for example, there are valid cache-control and max-age), it will be stored in the HTTP cache and available for current and future sessions. If the resource is not cacheable, it is not stored in the HTTP cache. Instead, it is cached in an in-memory cache and remains unchanged until it is used.

How does Chrome’s web stack handle preload and Prefetch priorities?

The following are the loading priorities of different resources in Chrome 46 and later in the Blink kernel.

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 images that have not been preloaded (” late “meaning after).

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 in the viewable window have higher priority than images that are not in the viewport, so at some point Chrome will try to be lazy about loading images that are not in the viewport. When a lower-priority image appears in the viewport, the image’s priority is increased (note that the image’s priority does not change after the layout is completed).

Resources preloaded with the “as” attribute will have the same resource priority as the resource type they request. For example, preload as = “style” will get the highest priority, while as = “script” will get low or medium priority. These resources also follow the same CSP policy (for example, scripts are bound by script-src).

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?

This is a small number of cases, but in general, a good one – 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 (between the SW cache and the network), preload will get a cache hit from the same resource.

Does this load method waste user bandwidth

Using preload or Prefetch can be a waste of user bandwidth, especially if the resource is not cached.

Preload resources that are not used will be warned in Chrome’s Console 3s after the onload event.

The reason for this warning is that you may be using Preload to try to preload and cache other resources to improve performance, but if those preloaded resources are not being used, then you are doing extra work for no reason. On mobile devices, this amounts to a waste of user traffic, so be careful what you preload.

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 to “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.

Use the “as” attribute for preload, otherwise it will not benefit from it.

If you do not provide a valid “as” when specifying what to preload (such as a script), you will eventually get it twice.

Preload fonts will be reloaded without Crossorigin. Make sure you add the Crossorigin attribute when you use preload to get fonts, otherwise it will be reloaded. He uses anonymous cross-domain mode for this request. This is recommended even if the font is in the same domain as the page. This also applies to other domain name retrieval (such as the default asynchronous retrieval).

Finally, while it does not result in two fetches, this is usually a good suggestion:

Instead of preloading all requested resources, use preload to tell the browser that the resources are needed so that it can get them early.

I should add all resources in the header of the pagepreload?

This is a good example of a tool, not a rule. The number of preload files depends on the network content, the user’s bandwidth, and other network conditions when other resources are loaded.

Preload files that may be needed early in a page. For scripts, preload your key module is good because it separates fetching from executing, whereas just using

Does Prefetch have any magic properties you should be aware of? Yes.

In Chrome, if a user navigates away from one page while prefetch requests to other pages are still in progress, they will not be terminated.

In addition, prefetch requests remain in an unspecified network stack cache for at least five minutes, regardless of the cacheability of the resource.

I’m using a custom “preload” in JS. How is it different from rel=”preload” or the preload header?

Preload decouples resources from JS processing and execution. Therefore, preload is declared in the tag to be scanned by the Chrome Preload scanner. This means that in many cases, the preload (with an indicated priority) will be fetched before the HTML parser even reaches the tag, making it more powerful than a custom preload implementation.

Isn’t it possible to replace preload with HTTP/2 server push?

Using a push when you know the exact load order of the resource and having the service worker intercept the request may cause the cached resource to be pushed again. Using Preload allows the resource to start downloading closer to the initial request – this is useful for all resource fetches.

Let’s say the browser is loading a page with a CSS file that references a font library. For this scenario,

In the case of HTTP/2 PUSH, when the server gets the HTML file and knows that the client will need the font file in the future, it immediately pushes the file to the client actively, as shown in the following figure:

In the case of preload, the server will not push the font file actively. It will only get the preload font after the browser finds the page, as shown in the following figure:

While push is effective, it doesn’t fit all situations like Preload does.

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 peload request header? How does it compare to the Preload tag? How does it relate to HTTP/2 server push?

Like other types of links, preload links can use EITHER HTML tags or HTTP headers. In either case, the preload link instructs the browser to start loading the resource into the in-memory cache, indicating that the page has a high probability of using the resource and does not want to wait for a preloaded 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.

1: preload is not used. 2: Preload is used

You can provide preload links in either form, but you should be aware of one important difference: many servers will trigger AN HTTP/2 server push when they encounter a preload link with an HTTP header, as the specification allows. HTTP/2 pushes have a different performance impact than normal preloading, 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 to judge the support situation?

const preloadSupported = () => { 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 use preload to make CSS styles work immediately?

Of course, preload supports tags based on asynchronous loading, and stylesheets that use can be immediately applied to the current document using the onload event:

<link rel="preload" href="style.css" onload="this.rel=stylesheet">
Copy the code

What other sites are using Preload widely?

According to HTTPArchive, most sites that use use it to preload Web fonts, including Teen Vogue and the aforementioned Shopify:

Other popular sites like LifeHacker and JCPenny use it to load their CSS asynchronously (via Filament Group loadCSS) :

It is then used by a growing number of progressive Web applications such as Twitter.com Mobile, Flipkart, and Housing to preload the scripts required for the current navigation (using patterns such as PRPL)

The basic idea is to maintain artifacts at a high level of granularity (rather than bundle them as a whole), 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, about 50% support, about 71%.

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

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Your likes are my motivation to keep sharing good things.

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.