当前位置:网站首页>Key rendering paths for performance optimization
Key rendering paths for performance optimization
2022-07-04 19:58:00 【Front end little witch】
*Don't ask again 「“ How could it be ”」, It's about asking 「“ Why not ”」
*
Hello everyone , I am a 「 Seven eight nine 」.
today , Let's talk about , Browser's 「 Critical render path 」. Some other articles for browsers , We have introduced . Respectively from the Browser architecture and The latest rendering engine This paper introduces the related concepts of page rendering . The corresponding connections are as follows .
How are pages generated ( Macro perspective ) Chromium The latest rendering engine --RenderingNG RenderingNG Key data structures and their roles in
And today's protagonist is Critical render path . It is affecting the page in 「 load 」 Main criteria of stage .
A little more verbose here , Usually a page has 「 Three stages 」
「 Loading phase 」 From 「 Send the request to render the complete page 」 The process of The main factors affecting this stage are 「 The Internet 」 and 「JavaScript Script 」
「 Interaction phase 」 Mainly from page loading to 「 User interaction 」 The whole process The main factor affecting this stage is 「JavaScript Script 」
「 Closing phase 」 It mainly refers to what the page does after the user sends the closing instruction 「 Cleanup operations 」
Okay , It's getting late . Open the door .
What you can learn
**
Various indicators of critical rendering paths Key resources : All possibilities 「 Block page rendering 」 Resources for Critical path length : Get all the key resources needed to build the page 「RTT」(Round Trip Time) Key bytes : Transmitted as part of completing and building the page 「 The total number of bytes 」. To relive HTTP cache Carry out various optimization treatments for key rendering paths in the light of React
Application for optimization
1. Key data in loading stage
Document object model
*「DOM」: yes
*HTML
The page is parsed , Object based representations .
DOM It's an application programming interface (API), By creating a tree representing the document , In one way 「 Independent of platform and language 」 To access and modify the content and structure of a page .
stay HTML
In the document ,Web Developers can use JS
Come on CRUD DOM structure , Its main purpose is 「 dynamic 」 change HTML Document structure .
*「DOM Will the whole
*HTML
The page is abstracted as a set of hierarchical nodes 」
「DOM Not only through JS visit 」, image Scalable vector graph 、 Mathematical markup language and Synchronous Multimedia Integration Language Have added the unique features of the language DOM
Methods and interfaces .
「 once HTML Be resolved , It will create a DOM Trees 」.
The following code has three areas :header
、main
and footer
. also style.css
by External file .
<html>
<head>
<link rel="stylesheet" href="style.css">
<title> Examples of critical render paths </title>
<body>
<header>
<h1>...</h1>
<p>...</p>
</header>
<main>
<h1>...</h1>
<p>...</p>
</main>
<footer>
<small>...</small>
</footer>
</body>
</head>
</html>
When the above HTML
The code is parsed by the browser as DOM Trees
Like structure , The relationship of each node is as follows .
Every browser 「 It takes some time to parse HTML」. also ,「 Clear semantic markers 」 Help reduce browser parsing HTML Time required .( Incomplete or incorrect semantic markers , The browser is also required to Context To analyze and judge )
Specifically , How the browser will HTML
String information , Convert to be able to be JS Operation of the DOM
object , Beyond the scope of this article . however , We can give a small example . In us JS Algorithm adventure stack (Stack) in , One question is How to judge the correctness of brackets .
*Given one only includes '(',')','{','}','[',']' String s , Determines whether the string is valid . Valid string needs to meet :
*
Opening parentheses must be closed with closing parentheses of the same type .
The left parenthesis must be closed in the correct order .
Example :
Input :s = "()[]{}" Output :true
Input :s = "(]" Output :false
Actually , The above example is the simplest tag matching . Or be safe , Their main ideas are consistent .
CSSOM Tree
**
CSSOM
It is also an object-based tree . it 「 Responsible for dealing with DOM Tree related styles 」.
Take on the above , We have here and above HTML
Form a complete set of CSS
style .
header{
background-color: white;
color: black;
}
p{
font-weight:400;
}
h1{
font-size:72px;
}
small{
text-align:left
}
For the above CSS Statement ,CSSOM Trees
It will be shown as follows .
because ,css
Some properties of can be 「 Inherit 」, therefore , Attributes defined in the parent node , If the situation is satisfied , Child nodes also have corresponding attribute information , Finally, the corresponding style information , Render to page .
*Generally speaking ,CSS Is considered to be a kind of Block rendering resources .
*
What is? 「 Render blocking 」? Rendering blocking resources is a Components , It will 「 The browser is not allowed to render the whole DOM Trees , Until the given resource is fully loaded 」.CSS
Is a rendering blocking resource , Because in CSS Before it's fully loaded , You can't render trees .
At first , All... On the page CSS
Information is stored in a file . Now? , Developers use some technical means , To be able to CSS
file 「 Division 」 Open ,「 Provide key styles only in the early stages of rendering 」.
perform JS
First of all, let's take a small knowledge point , Actually , In the previous article , We've already talked about it . here , Let's go over it again .
stay 「 In the browser environment 」,JS = ECMAScript + DOM + BOM
.
ECMAScript
JS Of 「 The core part of the 」, namely ECMA-262 The language of definition , It's not limited to Web browser .
Web
The browser is just ECMAScript
The realization of a possible Host environment . The hosting environment provides ECMAScript
Of 「 Benchmark implementation 」 And 「 Extensions necessary for the interaction of the environment itself 」.( such as DOM
Use ECMAScript
Core types and Syntax , Provides additional environment specific functionality ).
Like our common Web browser 、 Node.js And those that have been eliminated Adobe Flash All are ECMA
The host environment of .
ECMAScript
Just for implementation ECMA-262 A standardized title in a language , JS
Realized ECMAScript
,Adobe ActionScript
It also realizes ECMAScript
.
The above content is just a supplement to the knowledge points , What appears in our article JS
Or the general meaning : namely javascript
Text information .
「JavaScript
It's a kind of operation DOM
Language 」. these 「 The operation takes time 」, And increase the overall website Loading time . all ,
**
JavaScript
The code is called Parser blocking resources .
What is? 「 Parser blocking 」? When you need to 「 download 」 and 「 perform 」JavaScript
Code , Browser meeting 「 Pause execution and build DOM Trees 」. When JavaScript After the code is executed ,DOM The construction of the tree continues .
That's why , 「JavaScript
It's an expensive resource 」 That's what I'm saying .
Demonstration of examples
Here's a paragraph HTML
The demonstration results of the code , Some words and pictures are displayed . As you can see ,「 The display of the whole page only took about 40ms」. Even if there is a picture , The display time of the page is also shorter . This is because of the ongoing Drawing for the first time when ,「 Images are not considered a key resource 」.
remember ,
*Critical render path All are 「 About
*HTML
、CSS
andJavascript
Of 」
Now? , Add css
. As shown in the figure below , One 「 Additional requests are triggered 」 了 . Just load html
File time is reduced , But the total time for processing and displaying pages has increased by nearly 10 times . Why? ?
ordinary
HTML
It doesn't involve too much The resource acquisition and Analytical work . however ,「 about CSS file , Must build a CSSOM」.HTML
OfDOM
andCSS
OfCSSOM
Must be built . This is undoubtedly a time-consuming process .JavaScript
It is likely to queryCSSOM
. It means ,「 In the execution of any JavaScript Before ,CSS The file must be completely downloaded and parsed 」.
「 Be careful 」:domContentLoaded
stay HTML DOM
By 「 Triggered when fully parsing and loading 」. This event will not wait image
、 Son frame
Even the stylesheet is fully loaded .「 The only goal is for the document to be loaded 」. Can be in window
Add events in , To see DOM Whether it is parsed and loaded .
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM Parsed and loaded successfully ');
});
Even if you choose to use Inline scripts replace external files , The performance will not change much . Mainly because we need to build CSSOM
. If you consider using external scripts , You can add async
attribute . This will Unblock the parser .
Terms related to critical path
Key resources : All possibilities 「 Block page rendering 」 Resources for
Critical path length : Get all the key resources needed to build the page 「RTT」(Round Trip Time)
When using TCP
When the protocol transfers a file , becauseTCP
Characteristics of , This data is not transmitted to the server at one time , It needs to be split into data packets and transmitted back and forth many timesRTT
It's here 「 Round trip delay 」It is a network Important performance indicators Indicates that data is sent from the sender , Receive confirmation from the receiving end to the sender , 「 Total time delay experienced 」
Usually 1 individual HTTP
The data package of is in14KB
aboutThe first is the request HTML
resources , Suppose the size is6KB
, Less than14KB
, therefore 1 individual RTT You can solve it
as for JavaScript
andCSS
fileBecause the rendering engine has a 「 Pre resolved thread 」, On receiving HTML
After the data , The pre parsing thread will 「 Quick scanHTML
Key resources in data 」, Once it's scanned , Will immediately make a requestIt can be said that JavaScript
andCSS
yes 「 Make a request at the same time 」 Of , So their 「 Requests overlap 」, Calculate their RTT when , 「 Just calculate the data with the largest volume 」 That's all right.
Key bytes : Transmitted as part of completing and building the page 「 The total number of bytes 」.
In our first example , If it is ordinary HTML Script , The values of the above indicators are as follows
1 Key resources ( html
)1 individual RTT 192 Bytes of data
In the second example , One ordinary HTML And the outside CSS Script , The values of the above indicators are as follows
2 Key resources ( html
+css
)2 individual RTT 400 Bytes of data
If you want to optimize the critical rendering path in any framework , You need to work hard on the above indicators and improve them .
**
Optimize key resources
take JavaScript
andCSS
Change to inline form ( The performance improvement is not great )If JavaScript
The code doesn't haveDOM
perhapsCSSOM
The operation of , It can be changed tosync
perhapsdefer
attributeThe first screen content can be loaded first , Non first screen content adopts 「 Scroll load 」 Optimize the critical path length
「 Compress 」 CSS
andJavaScript
resourcesremove HTML
、CSS
、JavaScript
Some of the documents 「 The comment 」Optimize key bytes By reducing the number of critical resources 「 Number 」 And reduce key resources 「 size 」 Collocation to achieve Use CDN
To reduce the number of timesRTT
Duration
Reduce renderer blocking resources
Lazy loading
The key to loading is " Lazy loading ". Any media resources 、CSS
、JavaScript
、 Images 、 even to the extent that HTML
Can be lazy loaded . Each load 「 Limited page content 」, You can improve the critical rendering path .
Don't load the whole page when loading the page CSS
、JavaScript
andHTML
.contrary , Can be a button
Add an event listener , The script is loaded only when the user clicks the button .Use Webpack
To complete the lazy loading function .
Here are some uses of pure JavaScript The technology of lazy loading .
such as , Now another <img/>/<iframe/>
In these cases , We can use <img>
and <iframe>
label 「 Attached default loading
attribute 」. When the browser sees this tag , It will 「 Delay loading 」iframe
and image
. The specific syntax is as follows :
<img src="image.png" loading="lazy">
<iframe src="abc.html" loading="lazy"></iframe>
Be careful :loading=lazy
Lazy loading of should not be used on non scrolling views .
Can not make use of loading=lazy
In the browser of , You can use IntersectionObserver
. This API Set a root , And the root ratio is configured for the visibility of each element . When an element is visible in the viewport , It will be loaded .
*
IntersectionObserverEntry
Object provides information about the target element , There are six attributes . The meaning of each attribute is as follows .*
time
: When visibility changes , It's a high-precision timestamp , The unit is millisecondtarget
: Observed target elements , It's aDOM
Node objectrootBounds
: Information about the rectangular area of the root element ,getBoundingClientRect()
Return value of method , If there is no root element ( That is, scrolling directly relative to the viewport ), Then return to nullboundingClientRect
: Information about the rectangular area of the target elementintersectionRect
: Target element and viewport ( Or root element ) The information of the intersection areaintersectionRatio
: The visible proportion of the target element , namelyintersectionRect
OccupyboundingClientRect
The proportion of , 「 When fully visible 1, Less than or equal to when completely invisible 0」
We observe all that have .lazy
Class elements .When having .lazy
When the element of class is on the viewport , 「 The intersection rate will drop below zero 」. If the intersection rate is zero or below zero , Indicates that the target is not in the viewport . and , There's nothing to do .
var intersectionObserver = new IntersectionObserver(function(entries) {
if (entries[0].intersectionRatio <= 0) return;
//intersection ratio stay 0 On , It means that you can see
console.log(' Load processing ');
});
// Target DOM To deal with
intersectionObserver.observe(document.querySelector('.lazy));
Async, Defer, Preload
「 Be careful 」:Async
and Defer
Are properties for external scripts .
Use Async Processing script
When using Async
when , The browser will be allowed to download JavaScript
Do other things when using resources .「 Once the download is complete 」, Download the JavaScript
Resources will be executed .
JavaScript
yes 「 Asynchronous download 」 Of .The execution of all other scripts will be suspended . DOM Rendering will happen at the same time . 「DOM Rendering will only pause while the script is executing 」. Render blocked JavaScript Questions can be used async
Property to solve .
「 If a resource is not important , Don't even use async, Omit it completely 」
<p>... Before executing the script , What you can see ...</p>
<script>
document.addEventListener('DOMContentLoaded', () => alert("DOM Built !"));
</script>
<script async src=""></script>
<p>... The above script is finished , To see this content ...</p>
Use Defer Processing script
When using Defer
when ,JavaScript
Resources will be in HTML Downloaded when rendering . However ,「 Execution does not happen immediately after the script is downloaded . contrary , It will wait HTML The file is completely rendered 」.
The execution of the script only occurs after rendering . Defer
Can make your JavaScript Resources will never block rendering
<p>... Before executing the script , What you can see ...</p>
<script defer src=""></script>
<p>... This content is not js Blocked , That is to say, you can see immediately ...</p>
Use Prelaod Deal with external resources
When using Preload
when , It is used for HTML Files not in the file , But in rendering or parsing JavaScript or CSS When you file . With Preload
, The browser will download resources , It will be executed when resources are available .
Use Prelaod
. The browser will download the file , Even if it's unnecessary on your page .Too much preloading will slow down your page . When there are too many preloaded files , The inherent priority of using preload will be affected . 「 Only the files required on the first screen page can be preloaded 」. Preloaded files will not be found until other files are rendered . for example , You are in a CSS
Add a font reference to the file . stay CSS Before the file is parsed , The existence of fonts will not be known . If the font is downloaded in advance , It will speed up your website .「 Preloading is only used for <link>
label 」.
<link rel="preload" href="style.css" as="style">
<link rel="preload" href="main.js" as="script">
Write native (Vanilla) JS, Avoid using third-party scripts
Native JS It has good performance and accessibility . For a specific use case , You don't need to rely entirely on third-party scripts . Although these libraries can often solve a lot of problems , But relying on heavy libraries to solve simple problems will lead to the performance degradation of your code .
「 Our requirement is not to avoid using frameworks and writing 100% New code for . Our requirement is to use auxiliary functions and small-scale plug-ins .」
cache and invalid Content
If the resource is on your page Repeated use , Then loading them all the time will be a torture . This is similar to loading the website every time . Caching will help prevent this cycle . stay HTTP Response head Provide expiration information for content in , Load only when they expire .
HTTP cache
We were Internet scraps Http cache Just introduced , About http Cached knowledge points , I'll take it directly .
*「 Best and fastest 」 Our request is 「 No request 」
*
The browser to 「 Static resources 」 The cache of is essentially HTTP
Cache policy of the protocol , Which can be divided into 「 Mandatory cache 」 and 「 Negotiate the cache 」.
*Both caching strategies will 「 Cache resources locally 」
*
Force cache policy according to 「 Expiration time 」 Decide whether to use local cache or request new resources : Negotiation cache every time 「 Request 」, after 「 Compare servers 」 Then decide whether to use local cache or new resources .
What kind of caching strategy is used , from HTTP The first part of the agreement ( Headers
) Information determines .
stay Generation of network communication HTTP news We introduced , Message headers can be divided into 「 Four categories 」
1. Universal head : Header fields for requests and responses
2. Request header : Header field used to represent additional information of the request message
3. Response head : The header field used to represent additional information of the response message
4. Entity head : be used for 「 Message body 」 The header field of the additional information of
We are right. HTTP Cache the fields used for a simple classification and summary .
Header fields | The group to which it belongs |
---|---|
Expires | Entity head |
Cache-control | Universal head |
ETag | Entity head |
*ETag: stay 「 update operation 」 in , Sometimes it needs to be based on 「 Response data of last request 」 To send the next request . under these circumstances , This field can be used to provide the... Between the last response and the next request 「 The correlation information 」. Last response , The server will go through
*Etag
Send a unique ID to the client , In the next request, the client can passIf-Match
、If-None-Match
、If-Range
Field informs the server of this identity , In this way, the server will know that the request is related to the last response .
Of this field 「 Function and Cookie It's the same 」 Of , but Cookie It's Netscape (Netscape) Specifications developed by the company , and Etag It is the specification after standardization
Expires and Cache-control:max-age=x( Strong cache )
**
Expires
andCache-control:max-age=x
yes 「 Mandatory cache 」 Key information of strategy , Both are 「 Response header information 」( The back end is returned to the client ) Of .
Expires
yes HTTP 1.0
Added features , By specifying a 「 A definite point in time 」 As the expiration time of the cache resource , Before this point in time, the client will use the locally cached file to answer the request , Instead of sending entity requests to the server .
Expires
The advantages of :
Within the cache expiration time 「 Reduce 」 Client's HTTP request It saves client processing time and improves Web Application execution speed Less 「 Server load 」 And the consumption of client network resources
Corresponding syntax
Expires: <http-date>
<http-date>
It's a HTTP- date Time stamp
Expires: Wed, 24 Oct 2022 14:00:00 GMT
The above information specifies 「 Cache expiration time 」 by 2022 year 8 month 24 Japan 14 spot
**
Expires
One 「 A fatal flaw 」 yes : It specifies the time point in 「 Server shall prevail 」 Time for , however 「 The client determines the expiration 」 When will 「 Compare the local time with this time point 」.
If the time of the client and the server exist 「 error 」, For example, the server time is 2022 year 8 month 23 Japan 13 spot
, The time of the client is 2022 year 8 month 23 Japan 15 spot
, Then through the Expires
Controlled cache resources will 「 invalid 」, The client will send an entity request to obtain the corresponding resources .
In response to this question , HTTP 1.1
Added Cache-control
First information for 「 More accurate 」 Control the cache .
frequently-used Cache-control There are several kinds of information .
no-cache
:
UseETag
The response header tells the client ( browser 、 proxy server ) This resource first needs to be checked whether it has been modified on the server , It cannot be reused before . This 「 signify no-cache There will be a communication with the server 」, Ensure that the returned resource has not been modified , If not modified , There is no need to download this resource . conversely , You need to download it again .no-store
When dealing with the logic that resources cannot be cached and reusedno-cache
similar . However , There is an important between them 「 difference 」.no-store
Require resources to be requested and downloaded every time . When dealing with private information (private information) When , This is an important feature .public & private
public
Indicates that this response can be used by the browser and the intermediate buffer 「 Infinite cache 」, This information is not Not commonly used , The conventional scheme is to usemax-age
Specify the exact cache timeprivate
Indicates that this response can be cached by the user browser , however 「 No intermediate buffers are allowed 」 Cache it . for example , The user's browser can cache the user's private information HTML Webpage , butCDN
But cannot cache .max-age=<seconds>
Specify from 「 The moment of request 」 Start calculating , The maximum time that the cached copy of this response is valid ( Company :「 second 」) for example ,max-age=360
Indicates that the browser is in the next 1 Use the local cache of this response within hours , No entity request will be sent to the servers-maxage=<seconds>
s-maxage
Andmax-age
similar , there 「s」 For sharing , This instruction is generally only used forCDNs
Or other 「 Middle man 」(intermediary caches). This command will 「 Cover 」max-age
andexpires
Response head .no-transform
Intermediate agents sometimes change the format of pictures and files , So as to achieve the effect of improving performance .no-transform
The instruction tells the intermediate agent not to change the format of the resource
**
max-age
The specified is cached 「 time span 」, Not the point in time when the cache expires , It will not be affected by the time error between the client and the server .
And Expires
comparison , max-age
Sure 「 Control cache more accurately 」, And ratio Expires Yes 「 Higher priority 」
Under the mandatory cache policy ( Cache-control
Not specified no-cache
and no-store
) Cache judgment process
Etag
and If-None-Match
( Negotiate the cache )
**
Etag
yes 「 The server 」 String form of resource allocation 「 Unique identity 」, As 「 Response head 」 The information is returned to the browser
「 browser 」 stay Cache-control
Appoint no-cache
perhaps max-age
and Expires
After expiration , take Etag
Value through If-None-Match
As 「 Ask for the first 」 The message is sent to the server .
「 The server 」 After receiving the request , Compare the requested resources Etag
Whether the value changes , If not changed, it will return 304 Not Modified
, And allocate new ones according to the established cache strategy Cache-control
Information ; If resources change , will return 「 newest 」 Resources and Redistribution Of Etag
value .
If the browser is forced to use the negotiation cache policy , Need to put Cache-control
The first message is set to no-cache
, So you won't judge max-age
and Expires
Expiration time , thus 「 Each resource request will be compared by the server 」.
JS Cache the layer (ServerWorker)
In pure JavaScript in , You are free to use service workers
To decide whether to load data . for example , I have two documents :style.css
and script.js
. I need to load these files , I can use service workers
To determine whether these resources must be kept up-to-date , Or you can use caching .
stay Web Performance optimization Worker Threads ( On ) We have introduced about ServerWork
Detailed introduction . If you are interested , You can go and have a look .
When the user The first time you start a single page application , The installation will be performed .
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(
[
'styles.css',
'script.js'
]
);
})
);
});
When the user performs an operation
document.querySelector('.lazy').addEventListener('click', function(event) {
event.preventDefault();
caches.open('lazy_posts’).then(function(cache) {
fetch('/get-article’).then(function(response) {
return response;
}).then(function(urls) {
cache.addAll(urls);
});
});
});
Handle network requests
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open('lazy_posts').then(function(cache) {
return cache.match(event.request).then(function (response) {
return response
});
})
);
});
It's on paper , We must know that we must do it . truth , All understand , Let's take a look at the actual development , How to optimize . We press React
Development as an example .
React Optimization in application
Optimization is divided into two stages .
Before the application is loaded
The second stage is to optimize after the application is loaded
Stage 1 ( Before loading )
Let's build a simple application , It has the following structure .
Header
Sidebar
Footer
The code structure is as follows .
webpack-demo
|- package.json
|- package-lock.json
|- webpack.config.js
|- /dist
|- /src
|- index.js
|- Header.js
|- Sidebar.js
|- Footer.js
|- loader.js
|- route.js
|- /node_modules
In our application , Only when the user logs in , You should see the sidebar .Webpack
It's a good tool , Can help us carry out 「 Code splitting 」. If we enable code splitting , We can App.js
or Route
Component pair React
Conduct Lazy Load processing .
We distinguish the code according to the page logic . Only when required by the application , Will load these logic fragments . therefore , The overall weight of the code remains low .
for example , If Sidebar
Components are loaded only when the user logs in , We have several ways to improve the performance of our applications .
First , We can do it in 「 Routing level 」 Lazy loading of code . As shown in the following code , The code is divided into three logical blocks .「 Only when the user selects a specific route , Each block will be loaded 」. It means , our DOM You don't have to Sidarbar
Code as its 「Critical Bytes」 Part of .
import {
Switch,
browserHistory,
BrowserRouter as Router,
Route
} from 'react-router-dom';
const Header = React.lazy( () => import('Header'));
const Footer = React.lazy( () => import('Footer'));
const Sidebar = React.lazy( () => import('Sidebar'));
const Routes = (props) => {
return isServerAvailable ? (
<Router history={browserHistory}>
<Switch>
<Route path="/" exact><Redirect to='/Header' /></Route>
<Route path="/sidebar" exact component={props => <Sidebar {...props} />} />
<Route path="/footer" exact component={props => <Footer {...props} />} />
</Switch>
</Router>
}
similarly , We can 「 From the parent level App.js To achieve lazy loading 」. This makes use of React
Of 「 Conditions apply colours to a drawing 」 Mechanism .
const Header = React.lazy( () => import('Header'));
const Footer = React.lazy( () => import('Footer'));
const Sidebar = React.lazy( () => import('Sidebar'));
function App (props) {
return(
<React.Fragment>
<Header user = {props.user} />
{props.user ? <Sidebar user = {props.user /> : null}
<Footer/>
</React.Fragment>
)
}
Speaking of conditional rendering ,React
Allows us to load components with the click of a button .
import _ from 'lodash';
function buildSidebar() {
const element = document.createElement('div');
const button = document.createElement('button');
button.innerHTML = ' Sign in ';
element.innerHTML = _.join([' load Sidebar', 'webpack'], ' ');
element.appendChild(button);
button.onclick = e =>
import(/* webpackChunkName: "sidebar" */ './sidebar')
.then(module => {
const sidebar = module.default;
sidebar()
});
return element;
}
document.body.appendChild(buildSidebar());
In practice , It is important to 「 Write all the routes or components in the name Suspense In the components of 」, Load in a lazy way .Suspense
The function of is when lazy loaded components are loaded , Provide an 「 Back up content 」. Backup content can be anything , For example, a <Loader/>
, Or a message , Tell the user why the page has not been drawn .
import React, { Suspense } from 'react';
import {
Switch,
browserHistory,
BrowserRouter as Router,
Route
} from 'react-router-dom';
import Loader from ‘./loader.js’
const Header = React.lazy( () => import('Header'));
const Footer = React.lazy( () => import('Footer'));
const Sidebar = React.lazy( () => import('Sidebar'));
const Routes = (props) => {
return isServerAvailable ? (
<Router history={browserHistory}>
<Suspense fallback={<Loader trigger={true} />}>
<Switch>
<Route path="/" exact><Redirect to='/Header' /></Route>
<Route path="/sidebar" exact component={props => <Sidebar {...props} />} />
<Route path="/footer" exact component={props => <Footer {...props} />} />
</Switch>
</Suspense>
</Router>
}
Stage two
Now? , The application is fully loaded , Then comes the stage of reconciliation . All of the processing logic is React
Help us . The most important point is React-Fiber
Mechanism .
If you want to know React_Fiber, Please refer to our previous article .
Use the correct state management method
whenever React DOM Trees
When modified , It will 「 Force the browser to reflow 」. This will have a serious impact on the performance of your application . 「 Reconciliation is used to ensure that the number of re circulation is reduced 」. similarly ,React Use state management to prevent recurrence . for example , You have oneuseState()
hook.If you are using class components , utilize shouldComponentUpdate()
Life cycle approach .shouldComponentUpdate()
Must be inPureComponent
To realize . When you do ,state
andprops
Between 「 Shallow contrast 」. therefore , The chance of re rendering is greatly reduced .
utilize React.Memo
React.Memo
Receiving components , And willprops
Memorize . When a component needs to be re rendered , Will be carried out in 「 Shallow contrast 」. Due to performance , This method is widely used .
function MyComponent(props) {
}
function areEqual(prevProps, nextProps) {
// contrast nextProps and prevProps, If the same , return false, Rendering does not occur
// If it's not the same , Render
}
export default React.memo(MyComponent, areEqual);
If you use function components , Please use useCallback()
anduseMemo()
.
Postscript
「 Sharing is an attitude 」.
Reference material :
Critical render path Internet scraps Http cache React Official website
「 The full text after , Now that I see this , If it feels good , Give me a compliment “ Looking at ” Well .」
边栏推荐
猜你喜欢
HMM隐马尔可夫模型最详细讲解与代码实现
Huawei Nova 10 series supports the application security detection function to build a strong mobile security firewall
Euler function
公司要上监控,Zabbix 和 Prometheus 怎么选?这么选准没错!
SSRS筛选器的IN运算(即包含于)用法
Swagger突然发癫
node_ Exporter deployment
Comment utiliser async awati asynchrone Task Handling au lieu de backgroundworker?
c# .net mvc 使用百度Ueditor富文本框上传文件(图片,视频等)
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
随机推荐
Functional interface
需求开发思考
YOLOv5s-ShuffleNetV2
C language - Introduction - Foundation - grammar - process control (VII)
HDU 1372 & POJ 2243 Knight Moves(广度优先搜索)
Utilisation de la barre de progression cbcggprogressdlgctrl utilisée par BCG
c# . Net MVC uses Baidu ueditor rich text box to upload files (pictures, videos, etc.)
1002. A+b for Polynomials (25) (PAT class a)
Several methods of online database migration
Comment utiliser async awati asynchrone Task Handling au lieu de backgroundworker?
Kotlin classes and objects
Dark horse programmer - software testing - stage 08 2-linux and database-23-30-process port related, modify file permissions, obtain port number information, program and process related operations, Li
Master the use of auto analyze in data warehouse
Add namespace declaration
水晶光电:长安深蓝SL03的AR-HUD产品由公司供应
Crawler (6) - Web page data parsing (2) | the use of beautifulsoup4 in Crawlers
1009 Product of Polynomials(25 分)(PAT甲级)
2022 version of stronger jsonpath compatibility and performance test (snack3, fastjson2, jayway.jsonpath)
记一次 .NET 某工控数据采集平台 线程数 爆高分析
Hough transform Hough transform principle