当前位置:网站首页>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 .

And today's protagonist is Critical render path Critical Rendering Path. It is affecting the page in load Main criteria of stage .

A little more verbose here , Usually a page has Three stages

  1. 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
  2. Interaction phase
    • Mainly from page loading to User interaction The whole process
    • The main factor affecting this stage is JavaScript Script
  3. 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

*
  1. Various indicators of critical rendering paths
  2. Key resources Critical Resource: All possibilities Block page rendering Resources for
  3. Critical path length Critical Path Length: Get all the key resources needed to build the page RTT(Round Trip Time)
  4. Key bytes Critical Bytes: Transmitted as part of completing and building the page The total number of bytes .
  5. To relive HTTP cache
  6. Carry out various optimization treatments for key rendering paths
  7. in the light of React Application for optimization
*

1. Key data in loading stage

Document object model 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 SVG Mathematical markup language MathML and Synchronous Multimedia Integration Language SMIL 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 :headermain 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 .

DOM Trees
DOM Trees

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 .

CSSOM Trees
CSSOM Trees

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 Render-Blocking 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 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 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 Critical Rendering Path All are About HTMLCSS and Javascript 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 Of DOM and CSS Of CSSOM Must be built . This is undoubtedly a time-consuming process .

  • JavaScript It is likely to query CSSOM. 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 Critical Resource: All possibilities Block page rendering Resources for

  • Critical path length 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 , because TCP 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 times
    • RTT 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 in 14KB about
      • The first is the request HTML resources , Suppose the size is 6KB, Less than 14KB, therefore 1 individual RTT You can solve it
    • as for JavaScript and CSS file
      • Because the rendering engine has a Pre resolved thread , On receiving HTML After the data , The pre parsing thread will Quick scan HTML Key resources in data , Once it's scanned , Will immediately make a request
      • It can be said that JavaScript and CSS 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 Critical 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 and CSS Change to inline form ( The performance improvement is not great )
    • If JavaScript The code doesn't have DOM perhaps CSSOM The operation of , It can be changed to sync perhaps defer attribute
    • The first screen content can be loaded first , Non first screen content adopts Scroll load
  • Optimize the critical path length
    • Compress CSS and JavaScript resources
    • remove HTMLCSSJavaScript 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 times RTT Duration
*

Reduce renderer blocking resources

Lazy loading

The key to loading is " Lazy loading ". Any media resources 、CSSJavaScript、 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 CSSJavaScript and HTML.
  • 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 millisecond
  • target: Observed target elements , It's a DOM Node object
  • rootBounds: 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 null
  • boundingClientRect: Information about the rectangular area of the target element
  • intersectionRect: Target element and viewport ( Or root element ) The information of the intersection area
  • intersectionRatio: The visible proportion of the target element , namely intersectionRect Occupy boundingClientRect 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 <= 0return;

  //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 .

  1. JavaScript yes Asynchronous download Of .
  2. The execution of all other scripts will be suspended .
  3. DOM Rendering will happen at the same time .
  4. DOM Rendering will only pause while the script is executing .
  5. 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 .

  1. The execution of the script only occurs after rendering .
  2. 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 Caching and invalid Expiring 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 pass If-MatchIf-None-MatchIf-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 and Cache-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:
    Use ETag 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 reused no-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 use max-age Specify the exact cache time
    private 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 , but CDN 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 server

  • s-maxage=<seconds>
    s-maxage And max-age similar , there s For sharing , This instruction is generally only used for CDNs Or other Middle man (intermediary caches). This command will Cover max-age and expires 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 .

    1. Before the application is loaded
    1. 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 one useState()hook.
  • If you are using class components , utilize shouldComponentUpdate() Life cycle approach . shouldComponentUpdate() Must be in PureComponent To realize . When you do , state and props Between Shallow contrast . therefore , The chance of re rendering is greatly reduced .

utilize React.Memo

  • React.Memo Receiving components , And will props 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() and useMemo().

Postscript

Sharing is an attitude .

Reference material :

The full text after , Now that I see this , If it feels good , Give me a compliment “ Looking at ” Well .

原网站

版权声明
本文为[Front end little witch]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041731488751.html