Reduce network requests
Browser cache
Local storage
localStorage
- localStorage is a new local storage API in html5. The storage capacity supported in general browsers is 5M. It is only saved in the browser and does not participate in communication with the server.
- The data stored in localStorage has no expiration time and can only be cleared manually. Because the data is saved in the browser's local hardware device, this part of data still exists even if the browser is closed. The data can continue to be used the next time the browser is opened to access the website.
- localStorage is very simple to use. Common API s include setItem, getItem, removeItem and clear
//Add or set data items to localStorage localStorage.setItem("username", "John") //Get data from localStorage by key name localStorage.getItem('username') //Removes the data item with the specified key name from localStorage localStorage.removeItem('username') //Clear all data in localStorage localStorage.clear()
- It is worth noting that localStorage cannot cross domain and can only be read and written under the same source; Secondly, only string content can be stored in localStorage, so when you want to store data such as objects and arrays, you can use JSON.stringify to convert them into strings first, and JSON.parse to restore their data types when you use them
sessionStorage
- sessioStorage and localStorage are basically the same in API usage. The difference between them is that they have different data persistence. The data stored in sessioStorage is only available in the current session. When the tab is closed to end the session, the data will also be cleared
Application scenario
- Compared with sessioStorage, localStorage is more widely used. Due to the persistence of data in localStorage, it can be used to store some resources that are needed by websites and have stable content.
- For example, Taobao's localStorage stores many Base64 format picture strings (various small icons on the first screen)
- You can also use it to save search history, such as nuggets
- You can also save some local settings of the website, such as day / night mode of reading the website, font size, background color, etc
File merge
Merging and splitting of files
- You can use webpack
Sprite chart
- Sprite map splices multiple small icons into a large map. In the HTTP1.x environment, Sprite map can reduce HTTP requests and accelerate the display speed of web pages.
- The size of the icon used to synthesize sprite chart should be small, and it is not recommended to splice larger pictures into sprite chart; At the same time, if the website is a static icon, it is not an icon obtained dynamically through ajax request. Therefore, it is usually used as pictures such as website logo and icon.
- When you build with webpack, you can automatically synthesize sprite diagrams with the help of postcss sprites
Base64
- Base64 is not an image format, but an encoding method that converts any binary into a text string. When we encode an image with Base64, we convert the binary data of the image into a string
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAAAAXNSR0IArs4c6QAA...
- The Base64 encoding is directly used as the src attribute value of the < img > tag. The browser will automatically parse the Base64 encoding and will not initiate an image request again.
- Each time an http request is established, it will take a certain amount of time. For various small icons frequently used by the website, the time to establish an http request may exceed the time to download the image itself. In this case, Base64 can be used to encode small images to reduce http requests.
- Due to the principle of Base64 coding, Base64 coding is about 3 / 4 larger than the original image. If large images are encoded into html/css, the volume of the latter will increase significantly, which will significantly affect the opening speed of web pages. Therefore, it is generally recommended to perform Base64 encoding conversion only for small graphs.
- The URL loader in the webpack can automatically decide whether to perform Base64 encoding according to the file size
Reduce resource volume
- In addition to reducing network requests, reducing resource volume is another important optimization point and an essential link in our development process
Build tool optimization
- Using build tools to merge and compress resources is the most common operation in engineering practice. Nowadays, the most mainstream construction tool is undoubtedly webpack. We also mainly discuss the optimization of resource volume by using webpack
Select the appropriate picture format
- If possible, try to use CSS effects (gradients, shadows, fillets, etc.) instead of images
- When image resources must be used, it is very important to select the appropriate image format, because the same visual effect, different image sizes in different formats.
- jpg: lossy compression, small volume. It is suitable for presenting large pictures with rich colors, such as background map, rotation map, Banner map, etc.
- png: lossless compression, large volume, supporting transparency. It is suitable for small logos, pictures with simple color and strong contrast, etc.
- webp: launched by Google in 2010, it uses a better image data compression algorithm, with smaller image volume and no difference in image quality recognized by the naked eye; At the same time, it has the characteristics of lossless and lossy compression mode, supporting transparency and animation. But in terms of compatibility, IE and Safari browsers do not support it.
- svg: vector graph, the picture can be infinitely enlarged without distortion, and the volume is small. Applicable to various icon s and logo s
First screen resource loading optimization
- If all the contents outside the first screen are loaded at one time, the rendering speed of the first screen will be affected; Moreover, if the page is very long, even if the whole page is loaded, the user does not necessarily scroll the screen to browse the whole content.
- Therefore, a very important optimization point is that when opening the website, try to load only the resources contained in the first screen content, while the resources outside the first screen can be loaded when needed. So that the first screen content of the page can be rendered faster.
Lazy loading
Route lazy loading
- In a single page application, if all components are packaged together, the js package will become very large, which will affect the loading speed of the page when it is loaded for the first time. Using lazy routing loading, we can divide the components of different routes into different code blocks. When the route is accessed, the corresponding components will be loaded
- Using dynamic import, it is easy to implement lazy loading of routes
Lazy loading of pictures
- Whether the browser initiates a request for a picture is based on the src attribute of < img >. The principle of lazy loading is that it does not directly assign a value to the src attribute of < img >, but assigns a picture URL to src when < img > enters the visual area
- For each < img > tag that needs to be lazy loaded, set a data src attribute to store the image URL. When the element enters the visual area, get the value of this data src, and then assign it to the src attribute of < img >.
- So, how to judge whether < img > enters the visual area? Here, getBoundingClientRect is used to obtain the distance top between the top of the element and the top of the browser viewport. The height of the browser viewport is obtained through window.innerHeight. When the value of viewHeight - top is greater than or equal to 0, it indicates that the element has entered the visual area.
- Let's implement a simple lazy load.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .lazy{ height: 150px; width: 200px; background-color: #eee; } </style> </head> <body> <div> <img class="lazy" data-src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3176859023,1719957347&fm=26&gp=0.jpg"> </div> <div> <img class="lazy" data-src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2413205756,2857128339&fm=26&gp=0.jpg"> </div> <div> <img class="lazy" data-src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2356708534,2525790159&fm=26&gp=0.jpg"> </div> <div> <img class="lazy" data-src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1332858679,869019665&fm=26&gp=0.jpg"> </div> <div> <img class="lazy" data-src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2450079006,3171044776&fm=26&gp=0.jpg"> </div> <div> <img class="lazy" data-src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1181825476,2174805292&fm=26&gp=0.jpg"> </div> </body> <script> const imgs = document.querySelectorAll('.lazy') // Picture labels that need to be loaded const viewHeight = window.innerHeight // Visual area height // num is used to count which picture is currently displayed to avoid checking whether it enters the visual area from the first picture every time let num = 0 function lazyload(){ for(let i=num; i<imgs.length; i++) { // Subtract the distance between the top of the element and the top of the browser viewport from the browser viewport height let distance = viewHeight - imgs[i].getBoundingClientRect().top // If distance is greater than or equal to 0, the element enters the visual area if(distance >= 0 ){ // Get the picture URL stored in the data src attribute and assign it to the src attribute imgs[i].src = imgs[i].getAttribute('data-src') // The first i pictures have been loaded. Next time, start from i+1 to check whether they enter the visual area num = i + 1 } } } lazyload() //Load the picture to be displayed on the first screen window.addEventListener('scroll', lazyload, false) // Listen for scroll events </script> </html>
Server side rendering
- Vue, React and other frameworks make development simple and efficient, but also make the page need to load more resources. In addition to the business code, the page can not be rendered until the framework code is loaded. For websites with high requirements for the rendering speed of the first screen, server-side rendering can be considered. It can not only improve the rendering speed of the first screen, but also help SEO. The practice of server-side rendering is often closely combined with front-end frameworks (such as Vue, React, etc.).
Basic network optimization
DNS
- DNS is responsible for converting domain names to IP addresses. DNS optimization mainly includes the following two points:
- Reduce DNS queries
The DNS query results are cached locally by the client, so after the first query obtains the corresponding IP from the domain name server, the next access will directly obtain the IP address locally. Therefore, it avoids dispersing static resources under multiple domain names and reduces DNS queries with the help of domain name servers. - Preload
When browsing the web page, the browser will resolve and cache the domain name in the web page in the background when loading the web page, so there is no need to resolve DNS when accessing the connection in the current web page
You can control the pre parsing of all connections in the current page, or the pre parsing of specific connections, and configure them in the head tab//Pre resolve all connections in the current page <meta http-equiv="x-dns-prefetch-control" content="on">
//Pre resolve specific connections <link rel="dns-prefetch" href="//cdn.jsdelivr.net"> <link rel="dns-prefetch" href="//baidu.com">
CDN
- CDN is used to store static resources such as JS, CSS and pictures. Static resources have the characteristics of high access frequency and large traffic. CDN is an important means to speed up static resources. CDN principle and detail reference [front end dictionary] CDN brings these performance optimizations
Turn from https://juejin.cn/post/6958694686689067038