Preface
The author has been involved in project refactoring for nearly half a year, and extensively applied performance optimization and design patterns in the refactoring process. performance optimization and design patterns two aspects of knowledge, whether at work or interview are high-frequency application scenarios, taking advantage of this opportunity to participate in large-scale project refactoring, I carefully sort out some regular and must-use performance Optimization suggestions, and combined with the daily development experience to sort out all the
performance optimization suggestions that the author has practiced in Netease for four years and think are useful, and share them with you! (Due to limited space, the
design pattern will be dedicated to an article later)
Maybe some performance optimization suggestions are already well-known, but it does not affect this sharing. Of course, the author also lists some details that may not usually pay attention to.
Usually, people think that performance optimization is a disorderly application scenario, but in the author's opinion, it is an orderly application scenario and many
performance optimizations are for each other and even the Belt and Road Initiative. From the perspective of process trends,
performance optimization can be divided into network level and rendering level ; from the result trend,
performance optimization can be divided into time level and volume level . To put it simply,
should make it appear in front of users quickly and accurately when visiting the website.
All performance optimizations are implemented around
two major levels and two small levels, the core level is
network level and
rendering level, the auxiliary level is
time level and
volume level, and the auxiliary level is full of the core level. So we put together this article on the front
performance optimization nine strategies and six indicators . Of course, these
strategies and
indicators are defined by the author, so it is convenient to make some specifications for performance optimization in a certain way.
Therefore, combining these characteristics at work or interview can perfectly interpret the knowledge extended by performance optimization. high-energy in front, you have to store it if you don’t see it, go! ! !
所有代码示例为了凸显主题,只展示核心配置代码,其他配置并未补上,请自行脑补
Nine strategies
Network level
network level of is undoubtedly how to make the resource smaller and faster to load. Therefore, the author makes suggestions from the following four aspects.
- build strategy : based on build tools (
Webpack/Rollup/Parcel/Esbuild/Vite/Gulp
) - Image strategy : Based on image type (
JPG/PNG/SVG/WebP/Base64
) - distribution strategy : based on content distribution network (
CDN
) - caching strategy : based on browser caching (
strong caching/negotiation caching)
The above four aspects are all completed step by step, which is full of the entire project process. construction strategy and image strategy in the development stage, distribution strategy and cache strategy in the production stage, so you can check whether the above strategies are connected in order at each stage. In this way, the performance optimization application scenarios can be maximized.
Build strategy
This strategy mainly focuses on webpack
do related processing, and it is also the most common performance optimization strategy for access. The processing of other build tools is similar, and it may just be inconsistent in configuration. Speaking
webpack
of performance optimization, undoubtedly from
time level and
start volume level.
笔者发现目前webpack v5整体兼容性还不是特别好,某些功能配合第三方工具可能出现问题,故暂未升级到v5,继续使用v4作为生产工具,故以下配置均基于v4,但总体与v5的配置出入不大
performance optimization suggestions for the two levels, a total of 12
performance optimization suggestions, in order to facilitate memory, use four-character words to summarize, and make it easier for everyone to digest. ⏱ means
reduces packaging time, 📦 means
reduces packaging volume.
- reduces packaging time :
reduced scope,
cached copy,
directed search,
built in
parallel construction,
visual structure
- reduces the packaging volume :
segmentation code,
tree shake optimization,
dynamic gasket,
on-demand loading,
role enhancement,
compression resource
⏱Reduce scope
configures include/exclude to narrow Loader's search range for files . The advantage is that avoids unnecessary translation.
node_modules directory is so large, how much time does it cost to retrieve all the files?
include/exclude
is usually configured in the major Loader
, and the src directory is usually used as the source directory, which can be processed as follows. Of course,
include/exclude
can be modified according to the actual situation.
export default {
// ...
module: {
rules: [{
exclude: /node_modules/,
include: /src/,
test: /\.js$/,
use: "babel-loader"
}]
}
};
⏱Cached copy
configuration cache caches Loader's compiled copy of the file . The advantage is that when again, only the modified files are compiled. Why should the unmodified file be recompiled along with the modified file?
Most Loader/Plugin
will provide an option to use the compilation cache, usually containing the word cache
Take babel-loader
and eslint-webpack-plugin
as examples.
import EslintPlugin from "eslint-webpack-plugin";
export default {
// ...
module: {
rules: [{
// ...
test: /\.js$/,
use: [{
loader: "babel-loader",
options: { cacheDirectory: true }
}]
}]
},
plugins: [
new EslintPlugin({ cache: true })
]
};
⏱Directed search
configures resolve to increase the search speed of files . The advantage is that directs and specifies the necessary file path. If some third-party libraries are introduced in a regular form, errors may be reported or you want the program to automatically index certain types of files.
alias
maps the module path, extensions
indicates the file suffix, and noParse
filters non-dependent files. Usually alias
and extensions
are sufficient.
export default {
// ...
resolve: {
alias: {
"#": AbsPath(""), // 根目录快捷方式
"@": AbsPath("src"), // src目录快捷方式
swiper: "swiper/js/swiper.min.js"
}, // 模块导入快捷方式
extensions: [".js", ".ts", ".jsx", ".tsx", ".json", ".vue"] // import路径时文件可省略后缀名
}
};
⏱Build in advance
configures DllPlugin to package third-party dependencies in advance . The advantage is that completely separates the DLL from the business code and only builds the business code each time. This is an ancient configuration that
webpack v2
, but now webpack v4+
is not recommended to use this configuration, because the performance improvement brought by its version iteration is enough to ignore the benefits brought by DllPlugin
DLL means dynamic link library, which refers to a code library that can be used by multiple programs at the same time. In the front-end field, it can be considered as the existence of alternative caches. It packs common codes into DLL files and stores them in the hard disk. When repackaging, dynamically linking
DLL files does not need to repack those common codes, thereby increasing the construction speed and reducing packaging time.
Configuration DLL
generally more complicated than other configurations, and the configuration process can be roughly divided into three steps.
First tell the build script which dependencies are made into DLL
and generate DLL file and
DLL mapping table file.
import { DefinePlugin, DllPlugin } from "webpack";
export default {
// ...
entry: {
vendor: ["react", "react-dom", "react-router-dom"]
},
mode: "production",
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
chunks: "all",
name: "vendor",
test: /node_modules/
}
}
}
},
output: {
filename: "[name].dll.js", // 输出路径和文件名称
library: "[name]", // 全局变量名称:其他模块会从此变量上获取里面模块
path: AbsPath("dist/static") // 输出目录路径
},
plugins: [
new DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("development") // DLL模式下覆盖生产环境成开发环境(启动第三方依赖调试模式)
}),
new DllPlugin({
name: "[name]", // 全局变量名称:减小搜索范围,与output.library结合使用
path: AbsPath("dist/static/[name]-manifest.json") // 输出目录路径
})
]
};
Then package.json
and first execute the script before each build to package the DLL file.
{
"scripts": {
"dll": "webpack --config webpack.dll.js"
}
}
The last link DLL files and inform
webpack
can hit DLL file to the discretion reading. Use html-webpack-tags-plugin to automatically insert
DLL file when packaging.
import { DllReferencePlugin } from "webpack";
import HtmlTagsPlugin from "html-webpack-tags-plugin";
export default {
// ...
plugins: [
// ...
new DllReferencePlugin({
manifest: AbsPath("dist/static/vendor-manifest.json") // manifest文件路径
}),
new HtmlTagsPlugin({
append: false, // 在生成资源后插入
publicPath: "/", // 使用公共路径
tags: ["static/vendor.dll.js"] // 资源路径
})
]
};
For the time cost of those few seconds, I suggest a better configuration. autodll-webpack-plugin can also be used instead of manual configuration.
⏱Parallel construction
configures Thread to convert Loader single process to multi-process . The advantage is that releases the advantages of CPU multi-core concurrency. When using
webpack
build a project, there will be a large number of files that need to be parsed and processed. The construction process is a computationally intensive operation. As the number of files increases, the construction process becomes slower.
Run Node
in the webpack
is single-threaded model, is simply webpack
tasks need to be processed a piece of processing, can not handle more than one time task.
file reading and
calculation operations are unavoidable. Can
webpack
handle multiple tasks at the same time and use CPU
computer to increase the build speed? thread-loader will help you, start the thread CPU
There is a problem to pay attention to here. If the project files are not too many, do not use the performance optimization suggestion. After all, there will be performance overhead when multiple threads are turned on.
import Os from "os";
export default {
// ...
module: {
rules: [{
// ...
test: /\.js$/,
use: [{
loader: "thread-loader",
options: { workers: Os.cpus().length }
}, {
loader: "babel-loader",
options: { cacheDirectory: true }
}]
}]
}
};
⏱Visual structure
configures BundleAnalyzer to analyze the package file structure . The advantage is that finds out the cause of the excessive volume. In order to reduce the construction time by analyzing the reasons, an optimized solution can be obtained.
BundleAnalyzer
is the webpack
, which can visually analyze packaged file, the proportion of module volume, the module inclusion relationship, the module dependency relationship, whether the file is duplicated, the compressed volume comparison and other visual data.
You can use the webpack-bundle-analyzer configuration, with it, we can quickly find related problems.
import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";
export default {
// ...
plugins: [
// ...
BundleAnalyzerPlugin()
]
};
📦Split code
divides each module code and extracts the same part of the code . The advantage is that reduces the frequency of repeated codes.
webpack v4
uses splitChunks
instead of CommonsChunksPlugin
achieve code segmentation.
splitChunks
are many configurations for 060ee2913eccbd. For details, please refer to official website , where the author pastes common configurations.
export default {
// ...
optimization: {
runtimeChunk: { name: "manifest" }, // 抽离WebpackRuntime函数
splitChunks: {
cacheGroups: {
common: {
minChunks: 2,
name: "common",
priority: 5,
reuseExistingChunk: true, // 重用已存在代码块
test: AbsPath("src")
},
vendor: {
chunks: "initial", // 代码分割类型
name: "vendor", // 代码块名称
priority: 10, // 优先级
test: /node_modules/ // 校验文件正则表达式
}
}, // 缓存组
chunks: "all" // 代码分割类型:all全部模块,async异步模块,initial入口模块
} // 代码块分割
}
};
📦Tree shake optimization
deletes the unreferenced code project. The advantage is that removes duplicate codes and unused codes.
shake the tree to optimize for the first time in
rollup
, is rollup
core concept, and later in webpack v2
borrowed in use.
tree shaking optimization is only valid for
ESM specifications, and it is invalid for other module specifications.
tree shaking optimization is aimed at static structure analysis. Only
import/export
can provide static import/export functions.
ESM specification must be used when writing business code to allow
optimize the tree shake to remove duplicate code and unused code.
In webpack
, you only need to set the packaging environment to production environment to make the
tree shake optimization take effect. At the same time, the business code is
ESM specification, using
import
import the module, and export
export the module.
export default {
// ...
mode: "production"
};
📦Dynamic gasket
according to UA through the shim service. The advantage is that not need to pack the heavy code shim. Every build configuration
@babel/preset-env
and core-js
according to some demand Polyfill
packed in, which undoubtedly contributed to increased code size.
@babel/preset-env
provided by useBuiltIns
can import Polyfill
on demand.
- false : ignore
target.browsers
load allPolyfill
in - entry : Load part of
Polyfill
according totarget.browsers
Polyfill
that is not supported by the browser is imported, and the entry fileimport "core-js/stable"
) - Usage : The
target.browsers
and detection code will use ES6 portionPolyfill
loading incoming (no entry fileimport "core-js/stable"
)
It is recommended that you use dynamic gasket.
dynamic gasket according to browser
UserAgent
return current browser Polyfill
, the idea is based on the browser UserAgent
from browserlist
Find out what features your current browser lacks support in order to return these features Polyfill
. Students interested in this aspect can refer to the source code of polyfill-library and polyfill-service
Two dynamic gasket services are provided here. You can click the following link in different browsers to see the different output of
Polyfill
. Believe that IExplore
is still the most Polyfill
, it proudly said: I am me, a different firework.
- official CDN service : https://polyfill.io/v3/polyfill.min.js
- Ali CDN service : https://polyfill.alicdn.com/polyfill.min.js
Use html-webpack-tags-plugin to automatically insert dynamic gasket when packaging.
import HtmlTagsPlugin from "html-webpack-tags-plugin";
export default {
plugins: [
new HtmlTagsPlugin({
append: false, // 在生成资源后插入
publicPath: false, // 使用公共路径
tags: ["https://polyfill.alicdn.com/polyfill.min.js"] // 资源路径
})
]
};
📦Load on demand
the routing page/trigger function into a single file, and loads when it is used. The advantage is that reduces the burden of first-screen rendering. Because the more features of the project, the larger the package size, which leads to the slower the first screen rendering speed.
When the first screen is rendered, it only needs to correspond to JS code without other
JS code, so
can be loaded on demand.
webpack v4
provides the on-demand cutting and loading function of the module. With import()
can achieve the effect of reducing the package of the first screen rendering, thereby speeding up the first screen rendering speed. Only when certain functions are triggered will the JS code of the current function be loaded.
webpack v4
provides magic annotation naming cutting module. If there is no annotation, the cut module cannot distinguish which business module belongs to, so generally one business module shares the annotation name of
cutting module.
const Login = () => import( /* webpackChunkName: "login" */ "../../views/login");
const Logon = () => import( /* webpackChunkName: "logon" */ "../../views/logon");
Running the console may be error in package.json
of babel
access configuration in @ babel / plugin-syntax-Dynamic-Import can be.
{
// ...
"babel": {
// ...
"plugins": [
// ...
"@babel/plugin-syntax-dynamic-import"
]
}
}
📦Improved function
analyzes the dependencies between modules and merges the packaged modules into one function . The advantage is that reduces function declarations and memory costs.
enhance the role for the first time in
rollup
, it is rollup
core concept, and later in webpack v3
borrowed in use.
Before the function enhancement is enabled, there will be a large number of function closures in the constructed code. Due to the module dependency, it will be converted to
IIFE
webpack
packaged by 060ee2913ed0fe. A large number of function closure wrapping codes will increase the package size ( modules, the more obvious it is). The scope of the function created when running the code becomes more, which leads to greater memory overhead.
After opening the function enhancement, the constructed code will be placed in a function scope in the order of introduction, and some variables will be appropriately renamed to prevent variable name conflicts, thereby reducing function declarations and memory costs.
In webpack
, you only need to set the packaging environment to production environment to make
effective, or explicitly set
concatenateModules
.
export default {
// ...
mode: "production"
};
// 显式设置
export default {
// ...
optimization: {
// ...
concatenateModules: true
}
};
📦Compress resources
compresses HTML/CSS/JS code, compresses font/image/audio/video , the advantage is that more effectively reduces the packaging volume. Optimizing the code to the extreme may not be as effective as optimizing the size of a resource file.
For HTML
code, use html-webpack-plugin enable the compression function.
import HtmlPlugin from "html-webpack-plugin";
export default {
// ...
plugins: [
// ...
HtmlPlugin({
// ...
minify: {
collapseWhitespace: true,
removeComments: true
} // 压缩HTML
})
]
};
For the CSS/JS
code, use the following plugins to enable the compression function. Among them, OptimizeCss
based on the cssnano
package. Uglifyjs
and Terser
are official plug-ins of webpack
JS code needs to distinguish between
ES5
and ES6
.
- optimize-css-assets-webpack-plugin : Compress
CSS code
- uglifyjs-webpack-plugin : Compress
ES5
version ofJS code
- terser-webpack-plugin : Compress
ES6
version ofJS code
import OptimizeCssAssetsPlugin from "optimize-css-assets-webpack-plugin";
import TerserPlugin from "terser-webpack-plugin";
import UglifyjsPlugin from "uglifyjs-webpack-plugin";
const compressOpts = type => ({
cache: true, // 缓存文件
parallel: true, // 并行处理
[`${type}Options`]: {
beautify: false,
compress: { drop_console: true }
} // 压缩配置
});
const compressCss = new OptimizeCssAssetsPlugin({
cssProcessorOptions: {
autoprefixer: { remove: false }, // 设置autoprefixer保留过时样式
safe: true // 避免cssnano重新计算z-index
}
});
const compressJs = USE_ES6
? new TerserPlugin(compressOpts("terser"))
: new UglifyjsPlugin(compressOpts("uglify"));
export default {
// ...
optimization: {
// ...
minimizer: [compressCss, compressJs] // 代码压缩
}
};
Regarding the font/audio/video file, there is really no relevant
Plugin
for us to use, so we can only ask you to use the corresponding compression tool before publishing the project to the production server. For image files, most of the
Loader/Plugin
packages use some image processing tools, and some of the functions of these tools are hosted on foreign servers, which often results in installation failures. For specific solutions, please refer to the article "Talking about the dangerous pits of NPM mirroring" by the author for the answer.
In view of this, the author spent a little trick to develop a Plugin
used to webpack
. For details, please refer to tinyimg-webpack-plugin .
import TinyimgPlugin from "tinyimg-webpack-plugin";
export default {
// ...
plugins: [
// ...
TinyimgPlugin()
]
};
The above-mentioned construction strategy is integrated into the author's open source bruce-cli , which is a React/Vue application automation construction scaffold, its zero-configuration out-of-the-box advantages are very suitable for entry-level, intermediate, and rapid development projects For the front-end students of, you can also
brucerc.js
files. You only need to focus on the writing of business codes without paying attention to the writing of build codes, making the project structure more concise. For details, please poke here , remember to check the document when using, support a Star Ha!
Image strategy
This strategy mainly focuses on the image type to do related processing, and it is also the
performance optimization strategy with lower access cost. Just do the following two points.
- image selection : understand the characteristics of all image types and which application scenarios are most suitable
- image compression : use tools or scripts to compress it before deploying to the production environment
image selection
volume/quality/compatibility/request/compression/transparency/scene for each image type, so that we can quickly determine which type of image to use in which scene.
Types of | volume | quality | compatible | request | compression | Transparent | Scenes |
---|---|---|---|---|---|---|---|
JPG | small | in | high | Yes | Lossy | not support | Background picture, carousel picture, colorful picture |
PNG | Big | high | high | Yes | Lossless | stand by | Icon, transparency |
SVG | small | high | high | Yes | Lossless | stand by | Icon, vector illustration |
WebP | small | in | low | Yes | Both | stand by | See compatibility |
Base64 | It depends | in | high | no | Lossless | stand by | icon |
image compression can be completed in the above
construction strategy-compression resources, or you can use the tool yourself. Since most of the
webpack
image compression tools are either installation failures or various environmental problems ( you know), I still recommend using image compression tools before releasing the project to the production server, so that it runs stably and will not increase the packaging time.
Useful image compression tools are nothing more than the following. If there are better tools, please add them in the comments!
tool | Open source | toll | API | Free trial |
---|---|---|---|---|
QuickPicture | ✖️ | ✔️ | ✖️ | There are many types of compression, good compression texture, volume limitation, and quantity limitation |
ShrinkMe | ✖️ | ✖️ | ✖️ | There are many types of compression, general compression texture, no quantity limit, and volume limit |
Squoosh | ✔️ | ✖️ | ✔️ | There are few compressible types, general compression texture, no quantity limit, and volume limit |
TinyJpg | ✖️ | ✔️ | ✔️ | There are few compressible types, good compression texture, limited quantity and volume |
TinyPng | ✖️ | ✔️ | ✔️ | There are few compressible types, good compression texture, limited quantity and volume |
Zhitu | ✖️ | ✖️ | ✖️ | The compressible type is general, the compression texture is general, the quantity is limited, and the volume is limited |
If you don't want to drag image files back and forth on the website, you can use the author's open source image batch processing tool img-master instead, which not only has compression function, but also grouping function, marking function and transformation function. At present, all the projects that the author is responsible for are processed by this tool, and it has been cool to use!
image strategy may be able to complete all
construction strategies by processing one image, so it is a very cheap but extremely effective
performance optimization strategy.
Distribution strategy
This strategy mainly focuses on the content distribution network for related processing. It is also the
performance optimization strategy with higher access costs and requires sufficient financial support.
Although the cost of access is high, most companies will buy some CDN servers, so there is no need to worry too much about deployment, even if you use it. This strategy can play the best role of
CDN
by following the following two points as much as possible.
- CDN for all static resources : Determine which files are static resources during the development phase
- Put the static resources and the main page under different domain names : Avoid the request to bring
Cookie
content distribution network abbreviated as CDN , which refers to a set of servers that are distributed in various places and store data copies and can satisfy data requests based on the principle of proximity. Its core feature is cache and
back-to-origin, cache is to copy resources to
CDN server, back-to-origin is
resource expired / does not exist, request to the upper server and copy to
CDN server.
Using CDN
can reduce network congestion, improve user access response speed and hit rate. The intelligent virtual network built on the basis of the existing network, relying on the servers deployed in various places, through the central platform's scheduling, load balancing, content distribution and other functional modules, enables users to obtain the required resources nearby. This is the ultimate mission of CDN
Based on the CDN
of based on the 160ee2913ed9bc proximity principle of , all the static resources of the website can be deployed to the CDN server. What files are included in static resources? Generally speaking, they are resources that can be obtained without calculations generated by the server, such as
style files that
script files, and
multimedia files (fonts/images/audio/video).
If you need to configure the CDN server separately, you can consider Cloud OSS , Netease and Cloud Kodo , of course, you need to purchase the corresponding CDN service
. Due to space issues, there will be related tutorials for these configurations after purchase, so you can experience them yourself, so I won't describe them here.
The author recommends that you first choose Netease . After all, I still have confidence in my own products. I accidentally advertised my own products, haha!
Caching strategy
This strategy mainly focuses on the browser cache to do related processing, and also makes the
performance optimization strategy with the lowest access cost. It significantly reduces the loss caused by network transmission and improves the speed of web page access. It is a very worthwhile
performance optimization strategy.
As can be seen from the figure below, in order to browser cache, the strategy should follow the following five points as much as possible to maximize the
browser cache.
- consider rejecting all caching strategies :
Cache-Control:no-store
- considers whether the resource requests from the server every time:
Cache-Control:no-cache
- considers whether the resource is cached by the proxy server :
Cache-Control:public/private
- considers the resource expiration time :
Expires:t/Cache-Control:max-age=t,s-maxage=t
- Consider the negotiation cache :
Last-Modified/Etag
At the same time, the browser cache is also one of the high-frequency interview questions. The author thinks that the above mentioned nouns can be fully understood under different word
browser cache in
performance optimization.
cache strategy is implemented by setting the
HTTP
message, which is divided into strong cache/mandatory cache and negotiation cache/comparison cache . In order to facilitate the comparison, the author will use the legend to show some details, I believe you have a better understanding.
The entire cache policy mechanism is very clear,
first strengthen the cache, if the hit fails, then the negotiation cache is used. If it hits the
strong cache, directly use the
strong cache; if it misses the
strong cache, send a request to the server to check whether it hits the
negotiation cache; if it hits the
negotiation cache, the server returns 304 to inform the browser to use the
local cache, otherwise it returns
The latest resources.
There are two more commonly used application scenarios that are worth with the 160ee2913edbf4 caching strategy. Of course, more application scenarios can be made according to project requirements.
- frequently changes resources : Set
Cache-Control:no-cache
to make the browser send a request to the server every time, and cooperate withLast-Modified/ETag
verify whether the resource is valid - rarely change resources : set
Cache-Control:max-age=31536000
to hash the file name, when the code is modified, a new file name will be generated, and the latest file will be downloaded when the HTML file is introduced and the file name changes
Rendering level
rendering level is undoubtedly how to make the code parse better and execute faster. Therefore, the author makes suggestions from the following five aspects.
- CSS policy : Based on CSS rules
- DOM strategy : based on DOM operations
- blocking strategy : load based on script
- reflow redraw strategy : redraw based on reflow
- asynchronous update strategy : based on asynchronous update
The above five aspects are all completed when writing the code, which is full of the development phase of the entire project process. Therefore, in the development phase, you need to pay attention to every point involved in the following at all times, and develop good development habits. The performance optimization is naturally used.
The performance optimization
rendering level is more in the coding details, rather than the physical code. It is simply follow some coding rules, in order to
rendered levels
performance optimization to maximize the effect.
reflux redraw strategy in rendering level
performance optimization in the proportion of heavier, most conventional
one performance optimization. The Nuggets booklet "The Beauty of CSS" 160ee2913edd95 uses a whole chapter to explain 160ee2913edd96 redrawing
this chapter has been opened. For more details, please click here .
CSS strategy
nesting rules with more than three levels
- Avoid adding extra selectors
ID selector
- Avoid using
tag selector instead of
class selector
- Avoid using
wildcard selector, only declare rules for the target node
- Avoid repeated matching and repeated definitions, pay attention to the inheritable attributes of
DOM strategy
- Cache
DOM calculated attributes
- Avoid too many
DOM operations
- Use
DOMFragment
cache to batchDOM operations
Blocking strategy
- Scripting and
dependence DOM / other scripts is very strong: for
<script>
setdefer
- Scripting and
dependence DOM / other script is not strong: for
<script>
setasync
Reflow redraw strategy
- Cache
DOM calculation attributes
- Use class merging styles to avoid changing styles one by one
- Use
display
controlDOM display and hide, and offline
Asynchronous update strategy
- When modifying
DOM
in theasynchronous task, wrap it into a
Six indicators
According to the author out performance optimization of the importance and practicality division
nine strategies and
six indicators, they are in fact a section of living
performance optimization recommendations. Some
performance optimization suggestions then do not affect the access is not large, so I will
nine strategic positioning than
six indicators.
nine strategies of 160ee2913ee04d, it is still recommended to connect in the development and production stages. When the project is resumed, the six indicators
can be connected according to actual application scenarios.
six indicators
basically cover most of the details of 160ee2913ee06e performance optimization, which can be used as a supplement to the nine strategies
The author
index into the following six aspects according to the characteristics of
performance optimization suggestion.
- loading optimization : performance optimization that can be done when resources are loaded
- execution optimization : resource performance optimization during execution
- rendering optimization : performance optimization that can be done when resources are rendered
- style optimization : the performance optimization that can be done when coding style
- script optimization : performance optimization that scripts can do when coding
- V8 engine optimization : Performance optimization that can be done
V8 engine features
Load optimization
Perform optimization
Rendering optimization
Style optimization
Script optimization
V8 engine optimization
to sum up
performance optimization as a commonplace knowledge, will inevitably be encountered at work or interview. In many cases, it is not to think of a performance optimization suggestion to do or answer, but to have an overall understanding of this aspect, know why it is designed this way, and what effect the purpose of this design can achieve.
160ee2913ee250 performance optimization can one article, if you go into details, you may need to write two books to finish it. What this article can give you is a direction and an attitude, and apply what you have learned. I hope that reading this article will help you.
Finally, the author organizes all the content of this article into a high-definition brain map, because it is too large to upload, you can follow the author's personal public number IQ front-end and reply performance optimization to get a pocket knowledge map!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。