current position:Home>The difference between preload and prefetch and how to optimize in webpack projects

The difference between preload and prefetch and how to optimize in webpack projects

2022-06-24 08:16:54Army Zhou

preload And prefetch The difference between

  • preload It's a statement fetch, Sure Force the browser not to block document Of onload Request resources in case of events . preload As the name suggests, it is a preloading method , It declares a resource that needs to be submitted for loading to the browser by declaration , Execute immediately when the resource is actually used , You don't have to wait for the consumption of the network .
  • prefetch Tell the browser This resource may be needed in the future , But when to load this resource is determined by the browser . If you can predict user behavior , For example, lazy loading , Clicking on other pages is equivalent to preloading the required resources in advance .

Usage method :

<link rel="preload" href="/path/to/style.css" as="style">

stay HTTP Add... To the response header preload Field :

Link: <>; rel=preload; as=style

This way is better than through Link Way to load resources faster , The request starts to preload resources before it returns to the parsing page .

prefetch Pre judgment loading and preload It's the same way

And cache behavior

When resources are preload perhaps prefetch after , Will be transferred from the network stack to HTTP Cache and enter the memory cache of the renderer . If resources can be cached ( for example , There is an effective cache-control and max-age), It will be stored in HTTP In cache , Can be used for current and future sessions . If the resource is not cacheable , It will not be stored in HTTP In cache . contrary , It will be cached in the memory cache and remain unchanged until it is used .

side effect

Use... Correctly preload/prefetch Will not cause a second download , That is to say : When this resource is used on the page preload Resources haven't been downloaded yet , At this time, there will be no secondary download , Will wait for the first download and execute the script .

about preload Come on , Once the page is closed , It will stop immediately preload Access to resources , And for prefetch resources , Even if the page closes ,prefetch The initiated request will continue without interruption .

preload and prefetch The priority of the 、

preload use “as” Or use “type” Property to indicate the priority of the resource they request ( for instance preload Use as=”style” Property will get the highest priority ). No, “as” Properties are treated as asynchronous requests ,“Early” It means to be requested before all picture requests that are not preloaded (“late” It means that after )

for example ,preload as =“style” Will get the highest priority , and as =“script” Will get low priority or medium priority . These resources follow the same CSP Strategy ( For example, scripts are affected by script-src constraint ).

The following is the Blink Kernel Chrome 46 The loading priority of different resources in and later versions belongs to the author .

As you can see from the diagram :( With Blink For example )

  1. HTML/CSS resources , Its priority is the highest
  2. font Font resources , The priorities are Highest/High
  3. Image resources , If it appears in a viewport , Then the priority is High, Otherwise Low

and script Script resources are special , Different priorities , Scripts are asynchronous based on their location in the file 、 Delay or blocking get different priorities :

  1. The script that the network blocks before the first picture resource is in the network priority High
  2. The script that the network blocks after the first picture resource is in the network priority Medium
  3. asynchronous / Delay / Inserted script ( No matter where it is ) In the network priority is Low

When the page preload Already in Service Worker Cache and HTTP What happens when a resource is cached ?

This is relatively rare in all cases , But generally speaking , It would be a better situation —— If the resource does not exceed HTTP Cache time or Service Worker No initiative to reissue the request , Then the browser will no longer request this resource .

If the resources are HTTP In cache ( stay SW Between cache and network ), that preload Will get cache hits from the same resources .

Use preload or prefetch, It may waste users' bandwidth , Especially when the resource is not cached .

Not used preload Resources in Chrome Of console It will be in onload event 3s After the warning .

webpack Optimize it preload and prefetch

Single page application due to too many pages , It may cause the code to be too large , So that the opening speed of the home page is too slow . therefore Segmentation code , Optimizing the opening speed of the first screen is particularly important .

But all the technical means are not perfect . When we cut the code , First screen js The file size has been reduced a lot . But there is also a prominent problem :

That's when you jump to another page , You need to download the corresponding page js file , This leads to a very bad experience , Every time you click to visit a new page, you have to wait js File download , Then go to the request interface to obtain data . Frequently loading The experience of animation is really bad

So if we go to the home page , When the browser's free time is set in advance, the user may click on the page js file , So the first screen js The file size is controlled , And when you click on a new page , dependent js The file has been downloaded , There will be no more loading Animation .

Dynamic introduction js file , Realization code-splitting, Reduce the opening time of the first screen

Load according to the introduction , Just add a comment

  • Code segmentation comments :/*webpackChunkName: 'mp-supports'*/
  • prefetch notes :/* webpackPrefetch: true */

added , You can see webpack Black magic :

Use cases

const { default: lodash } = await import(/* webpackChunkName: "lodash" */ /* webpackPrefetch: true */ 'lodash');
// Multiple possible targets
  /* webpackInclude: /\.json$/ */
  /* webpackExclude: /\.noimport\.json$/ */
  /* webpackChunkName: "my-chunk-name" */
  /* webpackMode: "lazy" */
  /* webpackPrefetch: true */
  /* webpackPreload: true */

Originally, it can be overlapped

react project

//  After code segmentation react Components 
const Demo = asyncComponent(() => import(
 /*webpackChunkName: 'mp-supports'*/

//  Routing in 
<Route path="/" component={App}>
    <Route path="/brand" component={Demo} />

The life cycle of the home page component :

/  After the data fetched by the interface , Conduct prefetch
componentDidUpdate({ topics }) {
  if( topics.length === 0 && this.props.topics.length > 0 ) {
   //  implement prefetch, Note that only webpack 4 Version only prefetch function .
        /* webpackPrefetch: true */
        /*webpackChunkName: 'topic'*/

Reference article :

3 Code Splitting Patterns For VueJS and Webpack

Use Proload/Prefetch Optimize your application

Web performance optimization :Preload,Prefetch The use of and in Chrome Priority in

webpack in ,webpackPrefetch、webpackPreload and webpackChunkName What's the difference ?

Reprint This station article 《Preload And Prefetch And webpack How to optimize 》, Please indicate the source :

copyright notice
author[Army Zhou],Please bring the original link to reprint, thank you.

Random recommended