From a classic front-end interview question - talk about front-end performance optimization

 Programmer interview question bank sharing

1. Front-end interview question bank ( required for interview) Recommended: ★★★★★            

Address: Front-end interview question bank

2. Recommended front-end technology navigation      : ★★★★★

Address: Front-end Technology Navigation Daquan

3. Recommended color value conversion tools for developers    : ★★★★★

Address: Developer Color Value Conversion Tool

From a classic front-end interview question - talk about front-end performance optimization

What happens after entering a URL in the browser?

This is a very classic interview question, containing most of the basic knowledge points of the front end.

  1. The first step is to find the IP address of the domain name through DNS.
  2. In the second step, the browser sends an HTTP request to the web server according to the IP address obtained by parsing
  3. The third step server receives the request and processes it
  4. Step 4 The server returns a response
  5. Step 5: The browser decodes the response, parses html as dom, parses css as css-tree, and dom+ css to generate render-tree drawing
  6. Step 6 After the page is displayed, the browser sends an asynchronous request.
  7. Step 7 After the whole process is over, the browser closes the TCP connection.

Let's first summarize the performance optimization points in these steps:

  1. dns preload
  2. Reduce loaded files

1. DNS pre-resolution

DNS resolution also takes time, and the IP corresponding to the domain name can be obtained in advance through pre-resolution. This saves the time of looking up the IP through the domain name in the first step.

<link rel="dns-prefetch" href="//www.zhihu.com"> 

Second, reduce loading files, browser cache

Usually browser caching strategies are divided into two types: strong caching and negotiated caching, and caching strategies are implemented by  HTTP Header setting

Strong cache

Strong caching does not require a request interface. Every time an HTTP request resource is initiated, the browser's cache is used directly.

Strong caching can be achieved by setting two  HTTP Header : Expires and  Cache-Control . Strong caching means that requests are not required during caching, state codefor 200

Negotiate cache

Negotiating the cache requires a request interface, asking whether the file cached in the backend has changed. If it has changed, it can only be re-requested. If there is no change, the cache will be used directly.

  • If the cache expires, you need to initiate a request to verify whether the resource has been updated. Negotiation cache can be achieved by setting two  HTTP Header : Last-Modified and ETag
  • When the browser initiates a request to verify the resource, if the resource has not changed, the server will return  304 a status code and update the browser cache validity period.

Look at this problem from the loading of index.js

1. The first load, http request, the server returns normally

  • Returns the response header plus strong caching instructions
  • expires: web 11 Aug 2019 20:50:00 (expiration time)
  • cache-control : max-age=3000000 (timestamp, http1.1 accurate, high priority)
  • Both headers are backends that tell the browser how long this file will not expire.
  • The browser will save the file after receiving the above two headers

Re-request this file within 2.1 hours

  • The browser recognizes a strong cache hit, the request is not sent, and the local cache file is used directly, and the status code is 200 from cache
  1. After 2 hours, request the file again, the strong cache is invalid, and the negotiated cache is used
  • The browser will not send the request directly, but ask the backend, and the header will bring the request header
  • if-modified-since: date, ask the backend whether the file has been modified after this date
  • The backend tells that it has not been modified, and the cached status code is 304 not modified
  • The higher priority is the etag (fingerprint of the file), the content remains unchanged, and the fingerprint remains unchanged.

4. If the backend tells you that you have changed it, you can only reload it

How to Use Cache Efficiently

1. The cache time is too long

  • The release is online, and the client still uses the cache, so there will be bugs

2. The cache time is too short

  • Too many files are loaded repeatedly, wasting bandwidth

solve:

1. Template (html) cannot be cached

Strong buffering is for static resources, and dynamic resources need to be used with caution. In addition to server-side pages that can be regarded as dynamic resources, html that references static resources can also be regarded as dynamic resources. If such html is also cached, when these html are updated, there may be no mechanism to notify the browser that these html have Update, especially in applications with separated front and back ends, the pages are all pure html pages, and each access address may directly access html pages. These pages usually do not strengthen the cache to ensure that the browser always requests the latest server when accessing these pages. resource

2. File name + hash value

Use webpack to package when the content of the file changes. The hash value of the generated file name will also change, so the file name will change, and browsing will naturally re-request instead of using the file in the cache.

When the content of the file has not changed, the hash value remains unchanged, the file name remains unchanged, and the cached file is browsed without sending a request.

3. Reduce the number of loaded files, lazy loading of pictures

What is image lazy loading

When visiting a page, first replace the background image path of the img element or other elements with a path with a size of 1*1px image (so that it only needs to be requested once), when the image appears in the visible area of ​​​​the browser When the real path of the picture is set, the picture will be displayed. This is image lazy loading.

How to load images

    <div class="img-container">
        <img  data-src="./01.jpeg" alt="">
    </div>
    <div class="img-container">
        <img  data-src="./02.jpg" alt="">
    </div>
    <div class="img-container">
        <img  data-src="./03.jpeg" alt="">
    </div>

Just put the address in data-src into src.

imgs[i].src = imgs[i].getAttribute('data-src')

How to tell if an element is in view?

The distance of the element relative to the vertex (text) <= window height + scrolling distance

with complete code

<script>
    const imgs = document.querySelectorAll('img')
    // 获取可视区域高度
    const viewHeight = window.innerHeight || window.documentElement.clientHeight
    console.log(viewHeight,imgs)
    function loadImg(){
      for(let i=0; i<imgs.length;i++){
        console.log(imgs[i].getBoundingClientRect().top)
        let dis = viewHeight - imgs[i].getBoundingClientRect().top
        if(dis>0){
          imgs[i].src = imgs[i].getAttribute('data-src')
        }
      }
    }
    loadImg()
    window.addEventListener('scroll',loadImg)
  </script>

postscript:

This topic also involves a lot of knowledge points, such as TCP/UDP, the rendering process of browsing, redrawing and reflow (rearrangement), etc. If you are interested, I will talk to you about these contents next time.

 Programmer interview question bank sharing

1. Front-end interview question bank ( required for interview) Recommended: ★★★★★            

Address: Front-end interview question bank

2. Recommended front-end technology navigation      : ★★★★★

Address: Front-end Technology Navigation Daquan

3. Recommended color value conversion tools for developers    : ★★★★★

Address: Developer Color Value Conversion Tool

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/126430859