current position:Home>Webpack practice: increase the loading speed of a library by four times
Webpack practice: increase the loading speed of a library by four times
2021-08-26 00:36:35 【toln】
Project background
The project is a library used within the company , Use webpack package .(webpack edition : 5.40.0) It used to be using npm Package management in the form of , However, due to the large volume of the project after packaging , Affect the loading speed of the page , So I decided to give up npm Package management , Pack it into js file , adopt script Tag to reference . about npm Package and js file , Each has its own advantages and disadvantages .
type | advantage | shortcoming |
---|---|---|
npm package | Easy to do version management ; The citation method is simple | Cannot split when package size is too large ; Difficult to do load optimization |
js file | Easy to split modules , Do load optimization ; High citation flexibility | Version management is cumbersome ; The caller needs to choose the right time to load js file |
Because it is an internal package , And higher requirements for loading performance , So you can use js The way
Optimization steps
One 、 Dynamically import some modules
Some modules that are not necessarily used in the project and are relatively large , use webpack Reference by dynamic import in , This reduces the first loaded package volume . For example, before modification :
import module1 from './module1';
Copy code
After modification :
// Here we will use module1 object
const module1 = await import(
/* webpackChunkName: "module1" */ './module1'
);
Copy code
such webpack Will module1 Pack it up as a stand-alone js file . The file will only be loaded when you import it .
webpack It also supports Pre acquisition module , Is to load when the browser is idle , Instead of loading when you introduce . It's practical to <link>
label rel
Property preload
and prefetch
value .
Two 、 Module split
The previous method is only applicable to modules that will not be used immediately , But for some core modules, this method cannot be used . For example, in our project three.js, The volume of the module is also relatively large , Can pass webpack To configure optimization
Package it into a separate js file ,
// ...
optimization: {
// ...
splitChunks: {
cacheGroups: {
three: {
test: /[\\/]node_modules[\\/](three)[\\/]/,
name: 'three',
chunks: 'all',
priority: 2,
},
},
},
},
Copy code
Other larger modules can also be separated .
3、 ... and 、 Modify the module export method
The first two steps are mainly to split the module , The purpose is to realize delayed loading and parallel loading , This basically increases the loading speed
Now we need to modify the export mode of the module . use npm Package management is actually a process after packaging CommonJS module
, Internal use module.exports = myLibrary
export , And then use require('myLibrary')
Mode introduction . Now pack it up as a js Files are imported directly in the browser , So we need to myLibrary
Expose to global objects .( You can also use it AMD Or other browser supported module Syntax , But these methods are not used at present ), take webpack Of output.library.type
from commonjs
Change it to umd
:
library: {
name: 'myLibrary',
type: 'umd',
},
Copy code
Four 、 Deploy js file
We need to deploy the packaged product to the static server . To configure webpack Of publicPath:
// ...
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: `https://cdn.xxx.com/your/server/path`,
},
Copy code
After each package dist
Upload the directory to the server path https://cdn.xxx.com/your/server/path
Next . We are currently using gitlab Of CI/CD Complete automated deployment .
5、 ... and 、 Call... In a new way
Use dynamic loading script The way , The following is the loading function :
function loadScript(src) {
return new Promise((resolve, reject) => {
const scriptEle = document.createElement('script');
scriptEle.type = 'text/javascript';
// Dynamic scripts async The default is true, Set to false In order to execute ( Parallel loading )
scriptEle.async = false;
if (scriptEle.readyState) {
// IE
scriptEle.onreadystatechange = () => {
if (scriptEle.readyState == 'loaded' || scriptEle.readyState == 'complete') {
resolve();
}
};
} else {
scriptEle.onload = () => {
resolve();
};
scriptEle.onerror = () => {
reject(`The script ${src} is not accessible`);
};
}
scriptEle.src = src;
document.currentScript.parentNode.insertBefore(scriptEle, document.currentScript);
});
}
Copy code
Parallel loading and sequential execution are used , The order of execution is :
Runtime files --> Separated dependencies --> Master file
6、 ... and 、 Better use of cache
Use the hash value as the packaged file name , To ensure that the cache becomes invalid after modifying the file .
output: {
// ...
filename: '[name].[contenthash].js',
},
Copy code
It should be noted that , When we modify one of the files , The hash value of the packaged product corresponding to other files can also be changed .
for instance , Suppose there are three modules in the project and they are all packaged into three separate modules js file , Module dependencies are as follows :
When we changed module1, We only expect module1 Corresponding js File name hash value changed . In fact, the file names of these three files have changed . The reason is that we didn't package the runtime files separately , Changing the file name of one file will change the content of another file , Form a chain reaction . Use the following configuration :
optimization: {
runtimeChunk: 'single',
}
Copy code
In this way, a separate runtime file will be generated after packaging , This file also needs to be deployed and loaded ( Execute before executing other files ).
So we're modifying module1, Only module1 Corresponding js The name of the file and the runtime file has changed , To optimize the cache .
copyright notice
author[toln],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210826003630829f.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich