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:54【Army 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 :
adopt Link Label to create :
<link rel="preload" href="/path/to/style.css" as="style">
stay HTTP Add... To the response header preload Field :
Link: <https://example.com/other/styles.css>; 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 )
- HTML/CSS resources , Its priority is the highest
- font Font resources , The priorities are Highest/High
- 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 :
- The script that the network blocks before the first picture resource is in the network priority High
- The script that the network blocks after the first picture resource is in the network priority Medium
- 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 :https://webpack.js.org/api/module-methods/#magic-comments
Use cases
const { default: lodash } = await import(/* webpackChunkName: "lodash" */ /* webpackPrefetch: true */ 'lodash'); // Multiple possible targets import( /* webpackInclude: /\.json$/ */ /* webpackExclude: /\.noimport\.json$/ */ /* webpackChunkName: "my-chunk-name" */ /* webpackMode: "lazy" */ /* webpackPrefetch: true */ /* webpackPreload: true */ `./locale/${language}` );
Originally, it can be overlapped
react project
// After code segmentation react Components const Demo = asyncComponent(() => import( /*webpackChunkName: 'mp-supports'*/ './views/Brand' )) // Routing in <Route path="/" component={App}> <Route path="/brand" component={Demo} /> </Route>
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 . import( /* webpackPrefetch: true */ /*webpackChunkName: 'topic'*/ "../topic" ) } }
Reference article :
3 Code Splitting Patterns For VueJS and Webpack https://medium.com/js-dojo/3-code-splitting-patterns-for-vuejs-and-webpack-b8fff1ea0ba4
Use Proload/Prefetch Optimize your application https://github.com/happylindz/blog/issues/17
Web performance optimization :Preload,Prefetch The use of and in Chrome Priority in https://segmentfault.com/a/1190000018828048
webpack in ,webpackPrefetch、webpackPreload and webpackChunkName What's the difference ? https://www.cnblogs.com/skychx/p/webpack-webpackChunkName-webpackPreload-webpackPreload.html
Reprint This station article 《Preload And Prefetch And webpack How to optimize 》, Please indicate the source :https://www.zhoulujun.cn/html/webfront/SGML/html5/2020_0702_8505.html
copyright notice
author[Army Zhou],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/20210626190526636d.html
The sidebar is recommended
- JavaScript raw values and wrapper objects
- Application of Python simplehttpserver
- The problem of UMI & react packaging and deploying to non root directory and refreshing Error 404 is solved
- Is bootstrap or Vue the first choice for self-study
- Bootstrap react or bootstrap Vue
- One article can understand the detailed explanation of nginx operation. Are you still checking for omissions and filling vacancies!
- How to utilize the old front-end devices to the cloud through easycvr intelligent edge gateway devices to create AI course intelligent applications
- Introduction to web front end to actual combat: absolute path, relative path and root directory of HTML import file
- HTML basics form
- Shadow element CSS3 box shadow attribute
guess what you like
AngularJS Bootstrap
Angularjs contains
Angularjs animation
The nginx server sets the picture anti-theft chain to prohibit the picture from being linked outside
This is a cost-effective SUV. It costs less than 50 cents a kilometer, has a wheelbase of nearly 2.8 meters, and sells for only 79900 yuan_ Europe_ Plus_ Design
About nginx
How does endless restart the Go program without stopping?
http net::ERR_ HTTP2_ PROTOCOL_ Error error finding
On BOM and DOM (7): HTML DOM event object attributes and DOM event detailed list
Analysis and practice of HTML5 mouse drag sorting and resize implementation scheme
Random recommended
- On BOM and DOM (3): DOM node operation - element style modification and DOM content addition, deletion, modification and query
- Embrace cloud native, Tencent releases TCSs container security service!
- Is there any way for FC in react+ts to set the component of function keyword
- How to write the V-model of vue2/3 custom components?
- Error using vuescoll!
- When HTML accesses the parent directory, the file content cannot be displayed normally in the browser after reading
- How to embed tabelau in the front page of react
- Vue component communication data does not update rendering
- It is very convenient to use ECs to build a drawing bed and hexo one click deployment
- How does webstorm set the bootstrap auto prompt
- Nginx cross domain understanding, simulation and solution
- Front page exercise
- How to hide the value in El form item in Vue and set the value of input box to be read-only
- Springboot+vue to realize campus second-hand Mall (graduation design I)
- Node. JS installation
- Summary of 2022 blue team HW elementary interview questions
- Screenshot of angular page (scroll bar displays completely)
- JavaScript object field splicing
- How to repair garbled code in HTML
- Display CSV as a table in JavaScript (simple example)
- How to read files using JavaScript
- Example of JavaScript FileReader API processing files
- Springboot+vue project tourism information recommendation system [source code open source]
- Ultra wideband pulse positioning scheme, UWB precise positioning technology, wireless indoor positioning application
- Elementui used tabs to step on the pit
- Ant Design Vue - remove the input component border and the border blue shadow effect when getting focus
- Get httponly protected cookies across sub domains through XSS
- Coding specification - Vue project
- Code writing specification - Javascript
- Code specification - HTML
- Code writing specification - CSS
- CSS Notes 6
- Quickly set up PgSQL for serverless
- 404405 troubleshooting after Vue uses proxy packaging
- Vue3 TS learning
- What is the charm of python, which is warmly pursued by countless programmers?
- HTML Basics
- CSS Foundation
- CSS (PC side) three methods of traditional page layout
- Inline element, block element, inline block element