Front-end performance optimization is nothing more than two things:

  • Speed up resource requests
  • Improve interface rendering speed

So there are some strategies we can take when designing systems or writing code to optimize the user experience. For example, resource compression combines tree shaking, lazy loading, preloading, loading animations and skeleton screens, displaying images in Base64 or ICONS, interface optimization, gzip, etc.

Specifically, there are the following optimization directions:

  1. Reduce resource size
  2. Reduce the number of resource requests
  3. Avoid backflow and redrawing
  4. Optimized high frequency events
  5. Caching common data
  6. According to the need to load
  7. preload

Webpack configuration

Build optimization

The cache

webpack5

cache: {
  type: 'filesystem'.buildDependencies: {
    config: [ __filename ],
  },
},

Copy the code

DllPlugin

multithreading

  • happypack

Narrow down the search.

  • exclude/include

The output optimization

  • SplitChunks – Code merges and compresses and extracts common chunks
  • Tree shaking – Removes extra code that is not needed
  • According to the need to load

From entering URL to page presentation, we need to understand optimization points.

From entering the URL to presenting the page

  1. Url parsing
  2. The DNS
  3. TCP Establishing a connection
  4. Making an HTTP request
  5. Server response
  6. The browser parses and renders
  7. Page loading complete

Browser cache

Negotiate the cache
  • Last-modified/if-modified-since: For the first request, add last-modified to the respone header, and if-modified-since to the request header for the second request
  • Etag/ if-none-match: These two values are unique identifying strings for each resource generated by the server and will change whenever the resource changes; The process is similar to that of last-modified/if-modified-since, and he can be accurate to higher levels of seconds.

Negotiation cache means that the file is already cached, but whether to read from the cache requires negotiation with the server, depending on the field Settings in the request/response header. It is important to note that the negotiation cache still sends the request.

Mandatory cache
  • Expires: Indicates an absolute time that determines whether the client date Expires
  • Cache-control: determines whether the access interval is longer than 3600 seconds

Forced caching is when files are fetched directly from the cache without a request being sent.

  • The cache-control response header indicates whether the resource can be cached and how long the Cache will last.
  • The Etag response header identifies the version of the resource from which the browser can cache and query the server.
  • The last-Modified response header identifies when the resource was Modified, which the browser can then use to cache and query the server.
When do YOU store DIST and When do you store Memoey?
  • Larger files will be cached in DIST because memory is also limited and there is more space on disk
  • Smaller file js, images are stored in memory
  • CSS files generally have dist
  • In particular, the memory size is limited, and the browser will also store some JS files in DIST according to its own built-in algorithm
Using http2
  • multiplexing
  • The first compression

Page rendering

  • Parsing the HTML generates a DOM tree.
  • Parsing CSS generates a CSSOM rule tree.
  • Combine the DOM tree with the CSSOM rule tree to generate the render tree.
  • Traverse the render tree to start the layout, calculating the location size information for each node.
  • Draws each node of the render tree to the screen.

Rearrangement to redraw

Backflow/rearrangement

Backflow mainly refers to rendering where geometric properties need to be changed. The geometry of the render tree node changes, causing its position to change, resulting in recalculation to generate a new render tree. This is the main reason why backflow costs performance, because it recalculates the DOM generated.

redraw

Redraw refers to changes in appearance properties. It affects the appearance properties of nodes, but does not affect their geometry. But the change of geometry will definitely affect the change of appearance.

What actions will cause the rearrangement?
  • Add or remove visible DOM elements
  • Element position change
  • Element size change
  • Content change
  • Browser window size changed
How to reduce rearrangement redraw?
  • When changing styles in JavaScript, it is best not to write styles directly, but to change styles by replacing classes.
  • If you want to perform a series of operations on a DOM element, you can take the DOM element out of the document flow, modify it, and bring it back to the document. Hidden elements (display:none) or DocumentFragement are recommended for this solution.
  • Set the location using Transform Translate.

Memory management

Processes and threads

  • Process: The execution of a program, which occupies a unique piece of memory, is the basic unit of the operating system.

    • A process has at least one running thread: the main thread. The process is automatically created after it starts.
    • A process can also run multiple threads at the same time, the program is multithreaded.
    • Data within a process can be shared by multiple threads. Data between multiple processes cannot be shared directly.
  • Thread: a unit of independent execution within a building. It is the smallest unit of CPU scheduling and the basic unit of program execution.

  • Thread pool: A container that holds multiple thread objects for reuse.

Why is JS single threaded

JavaScript is single-threaded in order to avoid repeated and unpredictable changes in page content during execution.

When JavaScript runs a block of code, other things on the page (UI updates or other script loading execution, etc.) are suspended at the same time and cannot be processed at the same time. Therefore, when executing a js script, this code will affect other operations.

The garbage collection

This is considered garbage in JavaScript:

  • Objects are no longer referenced as garbage
  • Objects cannot be asked from the root to be garbage

Memory optimization

  1. Be careful with global variables
  2. Avoid closure traps
  3. Choose the optimal loop method
  4. The garbage collection
  5. Reduce the nested
  6. Tail recursive optimization

Performance testing

LightHouse

other

Throttling and anti-shaking

Anti – shake: only the last event is executed in the set time, the previous events are cleared


const debounce=(func,wait=60) = >{
  let timer=null;
  return function (. args){
    clearTimeout(timer);
    timer=setTimeout(() = >func.apply(this,args),wait);
  };
};

Copy the code

Throttling: Only the first event is executed for a set time, after which the current time is set to the start time


const throttle=(func,delay=60) = >{
  let start=0;
  return function (. args){
    const current=+new Date(a);if(current-start>delay){
      func.apply(this,args); start=current; }}; };Copy the code

Load the animation and skeleton screen

Avoid page stuttering or flickering.

Image optimization

Sprite, Base64, ICONS…

Tail recursion

When a function calls itself (or a function that calls itself, and so on) at the end, this is called tail recursion.

The last call is the last operation of the function, so there is no need to keep the call record of the outer function, because the call location, internal variables and other information will not be used, as long as the call record of the inner function is directly replaced by the call record of the outer function. Optimize the call stack to save memory.

memoize

const memoize=(fn,len=100) = >{
  let cache=[];
  return (. args) = >{
    const key=JSON.stringify(args);
    const cached=cache.find(v= >v.key===key);
    if(! cached){constresult=fn(... args); cache.push({key,result});if(cache.length>len){
        cache.shift();
      }
      return result;
    }
    return cached.result;
  };
};

Copy the code

Virtual list

Render only visual window content.

The react to optimize

  • Narrow your dependency
  • Avoid deriving state
  • Use IMmutable data
  • Using useMemo

Pay attention to my

Wechat search for “Front-end Dao Meng”