Web front end performance optimization principle

Time:2020-1-27

(add stars to the front end of dada to improve the front end skills)

Web front end performance optimization principle

In order to be a qualified web front-end engineer, web front-end performance optimization is a must to master knowledge, so how to optimize web front-end performance? –Dada front end

Principle of web front end performance optimizationWeb front end performance optimization principle

Front end performance optimization, resource merging and compression, principle of image coding, and type selection, browser rendering mechanism, lazy loading, preloading, browser storage, caching mechanism, PWA and Vue SSR, etc.

Technology stack, vue.js and chrome, debugging tools performance and layers. Then what is the point of the front-end performance optimization principle, involving the role and principle, how to combine with the real project scenario, theory and practical experience, and carry out quantitative analysis.

The front-end optimization is generally the basic optimization (picture coding principle, etc.), the higher point is the advanced optimization (browser rendering mechanism, browser storage, optimization), combined with the server optimization (first screen rendering, etc.).

Front end performance optimization scheme, minimize HTTP requests, use content delivery network, avoid empty SRC or href, add expired or cache control header, gzip component, put stylesheets at the top, script at the bottom, avoid CSS expression, reduce DNS lookup, set JS and CSS as external, avoid redirection, configure Etag, use Ajax cache, reduce DOM element The number of elements, no 404, reduces the size of cookies, does not scale the images in HTML, avoids using filters, and uses favicon.icon, which is small and cacheable.

Interrogate the interviewerWeb front end performance optimization principle

Interviewer: why is front-end optimization? How is the picture decoded in the front end? How does the browser render load? What is the principle of lazy loading and preloading? What are the application scenarios of lazy loading and preloading? What are the principles of PWA and vue-ssr?

What is the principle of each optimized performance that the interviewer deeply questions? What is the principle of performance optimization combined with your own projects? What’s your experience after using performance optimization in the project? Talk about the most appropriate scenario process for each performance optimization principle.

Interviewers want to know how many performance optimization principles you master, whether you have used performance optimization in projects, analyze projects you have done, find points that need performance optimization, and select appropriate performance optimization.

There are images, style sheets, scripts, flash, etc. that affect the performance of the front-end. Reduce the number of components and the number of HTTP requests required to speed up the page.

Web front end performance optimization principle

Front end performance optimization, resource merging and compressionWeb front end performance optimization principle

Merging files is a way to reduce the number of HTTP requests by merging all scripts into one script, similar to merging all CSS into one stylesheet.

To achieve performance optimization, first, reduce the number of our HTTP requests, and reduce the resource size of the request. Second, what is the principle of resource compression and merging. What is the effect before compression and consolidation, and what is the difference between compression and consolidation.

Torture:What is the process of a browser request from sending to returning?Web front end performance optimization principle

Web front end performance optimization principle

URL decomposition, protocol name, mark symbol of hierarchical URL, fixed, credential information needed to access resources, which server to get data from, port number to connect, hierarchical file path to resources, query string, fragment ID.

Client, HTTP application layer, TCP transmission layer, IP network layer, data link layer network

The layers from high to low are application layer, transmission layer, network layer and data link layer. The sender goes down from the application layer and the receiver from the data link layer.

Application layer client sends HTTP request, message header, blank line, message body, message header including request line, request header field, entity header field, others.

Syn (synchronize sequence numbers)

ACK (acknowledgement) confirmation character

In the process, the user first enters a URL in the browser, and the core code in the browser will split and parse the entered URL, and then pass the domain to the DNS server. The DNS service will query the IP address corresponding to the relevant post according to the domain, and then pass the IP address to the browser. If the browser has an IP address, it will know where the browser is going, and if it holds an IP address, it will know this Ask where to send it. Just follow the protocol, the requested parameters will be carried in the protocol, sent to the network, and then through the LAN, switch, router, backbone network, to the server.

The server side has an MVC architecture. The request will first enter the controller, perform relevant logic processing and request distribution in the controller, call the model layer to interact with the data, and the model layer will read the data in redis and DB. Then it is sent to the network through the view layer, from the service end to the browser end. The browser is mainly the process of rendering. The render process is the process of rendering HTML, CSS, JavaScript, etc. requested by the browser, which will form the relevant DOM tree and the corresponding CSS tree, and render the corresponding style on the page.

In the process from browser to server, which processes can be optimized for our front-end?Web front end performance optimization principle

Client browser communicates with server through HTTP protocol, HTTP protocol belongs to application layer protocol, HTTP belongs to TCP protocol, so client communicates with server mainly through socket.

TCP belongs to the transport layer protocol. HTTPS requires TLS, SSL and other protocols in the session layer.

Browser, DNS server, server, etc. we can cache on DNS to optimize the front-end performance, router level, URL level for data caching, so the access time will be shortened a lot.

The process of network request, bandwidth, and network selection involve caching. CDN can be used. CDN is used to request static resources. If static resources are requested, then cookies are useless. Therefore, we hope to remove this cookie in the request of static resources. Here, we should pay attention that the domain name of CDN should not be the same as the domain name of the main station to prevent cookies from being carried.

How to reduce the size of our HTTP requests? Every HTTP request needs to go through the network environment to reach our server. Every request has the loss of the network environment. Reduce the number of HTTP requests to one time, and reduce the loss of the network environment. You can also start from the server side, first render the effect reflected in the page, and then go straight out to the web page.

Every request has the loss of network environment. We can combine multiple HTTP requests into one, so as to reduce the same environment loss.

Bandwidth, if the size of an HTTP request can be smaller, the access will be faster. In the rendering process of the browser, when using the framework, you need to render from the browser. The templates in the framework are to be rendered in the browser. This rendering in the framework is not conducive to the first screen, has a great loss on the first screen, and is not conducive to the performance of the front end.

The server renders HTML directly to our browser page, not in the browser.

Front end performance optimization point, through the process of HTTP request, we can learn that we can cache through DNS to reduce the time of DNS query. The process of network request follows the nearest network environment, with the same static resources for caching, reducing the size of HTTP request, reducing HTTP request, server-side rendering, and front-end optimization point from business.

Key point: if you have a deep understanding of HTTP request process, you can know the key points of front-end performance optimization

Merging and compression of resourcesWeb front end performance optimization principle

Reduce resource volume, gzip compression, JS obfuscation, CSS compression, image compression.

Reducing the number of HTTP requests is called merging, and reducing the size of HTTP requests is called compression. It can compress HTML, CSS, JS, merge files, open gzip, etc.

HTML compressionWeb front end performance optimization principle

The first is to use online website compression, HTML minifier tool for compression, and backend template engine for rendering compression.

CSS compressionWeb front end performance optimization principle

CSS sprite is the preferred method to reduce the number of image requests, combining background images into a single image.

CSS sprites is called CSS sprites by many people in China. It is a kind of web image application processing method. It allows you to include all the sporadic pictures involved in a page into a large picture, so that when you visit the page, the loaded pictures will not be slowly displayed one by one as before. For the current network popular speed, the loading time for a single image of no more than 200KB is almost the same, so there is no need to worry about this problem.

The first is to delete the invalid code, the second is to merge the CSS semantics, use online website compression, use HTML minifier to compress the CSS in HTML, and use clean CSS to compress the CSS.

Use the cssbackground image and background position properties to display the required image segments

Compression and confusion of JSWeb front end performance optimization principle

The first is to delete invalid characters, remove annotations, reduce and optimize code semantics, protect code, and compress using online websites, HTML minifier to compress JS in HTML, and uglifyjs2 to compress JS

(1) Change table to div layout

(2) Reduce the series labels of compact div, span, UL, Li, etc

(3) Remove extra space

(4) Use table to replace div layout properly

(5) Gzip compression of web page

Consolidation of documentsWeb front end performance optimization principle

There are inserted uplink requests between files, increasing n-1 network delay, which is more seriously affected by packet loss, and may be disconnected when passing through the proxy server. The merged file has the problem of first screen rendering and cache failure. JS file is relatively large and the request is relatively slow. Only after the request comes back can the first screen HTML render. JS is cached. File merging if one of the JS files changes, it will lead to cache failure. If the file is not merged, modifying one of the JS files will only lead to cache failure. Others Will not be affected. There is a serious cache invalidation problem in file merging.

So whether to merge files? It is recommended to pack public libraries into a file, business into a file, and different pages into different JS packages,

How to merge files, online website, and nodejs

The sum and compression of actual combat resourcesWeb front end performance optimization principle

Practical page development, website compression and merging, FIS automatic compression and merging.

Before compression

Web front end performance optimization principle

After compression

Web front end performance optimization principle

The construction of front-end automation realizes compression and mergingWeb front end performance optimization principle

Fis3 is a build tool in Baidu. Start – > getsource() – > whether all files are compiled (single file compilation, another process of packaging).

Fis3 configuration file, fis-conf.js

Web front end performance optimization principle

After compression, the performance before and after optimization should be better, and the large resource effect is obviousWeb front end performance optimization principle

Load optimization, merge CSS, JavaScript, merge small pictures, cache all resources that can be cached, use external style to reference CSS and JavaScript, compress HTML, CSS, JavaScript, enable gzip, use first screen loading, on-demand loading, scrolling loading, increase loading progress bar, reduce cookies, avoid redirection, load third-party resources asynchronously.

CSS optimization, CSS in the head, JavaScript in the tail, avoid empty SRC of pictures and frames, try to avoid resetting picture size, try to avoid using dataurl for pictures, try to avoid writing style attribute in HTML tags, avoid expression of CSS, remove empty CSS rules, correctly use display attribute, do not abuse float, do not abuse web font, do not abuse too many font-s Size, a value of 0 does not need any units, standardizes various browser prefixes, and avoids making selectors look like regular expressions.

Rendering optimization, HTML use viewport, reduce DOM nodes, try to use CSS3 animation, reasonably use requestanimationframe animation instead of setTimeout, properly use canvas animation, touchmove, scroll events will lead to multiple rendering, use CSS3 transitions, CSS3 3D, transforms, opacity, canvas, etc. to trigger GPU rendering.

Script optimization, reduce redrawing and reflow, cache DOM selection and calculation, cache list length, try to use event agent, avoid batch binding events, try to use ID selector, use touchstart and touchend instead of click.

Picture optimization, using CSS3, SVG, iconfont instead of picture, using srcset, web excellent and JPG, PNG8 is better than GIF, the first load is no more than 1014kb, picture is not wider than 640.

Note that when we modify the back-end response time in half, the overall response event can only be reduced by 5-10%, while when we optimize the front-end performance in half, the overall response can be reduced by 40-45%.

The meaning of front-end Optimization: the process of HTTP request is the core compression and merging principle for optimization

The process of picture optimizationWeb front end performance optimization principle

Image loading processing, image preloading, image lazy loading, display of progress bar when loading the first screen. The optimization of asynchronous requests, the use of normal JSON data format for interaction, part of the commonly used data cache.

Image mapping merges multiple images into one image with the same overall size, but reducing the number of HTTP requests can speed up the page.

Differences between PNG8, png24 and png32

PNG8 is 256 colors, supporting transparency, png24 is the 24 power of 2, not supporting transparency, png32 is the 24 power of 2, supporting transparency.

Jpg has lossy compression, high compression rate, does not support transparency, PNG supports transparency, browser compatibility is good, webp compression is better, there is compatibility problem in IOS WebView, SVG vector map, code embedding, relatively small.

Jpg usage scenarios are used in scenarios where transparent pictures are not needed, PNG usage scenarios are used in scenarios where transparent pictures are needed, webp is used in Android, and SVG vector images are used in relatively simple businesses with picture styles.

CSS sprite map integrates some pictures into a single picture to reduce the number of requests. The problem is that the picture is large. If it is not loaded successfully, it is slow and problematic. Image inline, which embeds the content of the picture in HTML and exists with HTML. As the format of Base64, it can reduce the number of HTTP requests for your website. Using vector graph SVG, drawing function, using iconcont to solve icon problem.

Webp is used in Android, it has better image data compression algorithm, lossless and lossy compression mode, alpha transparency, animation characteristics.

HTML rendering process: sequential execution (lexical analysis), concurrent loading, blocking, dependency, introduction mode.

CSS blocking, CSS head blocking page rendering, CSS blocking the execution of JS, CSS does not block the loading of external scripts.

JS blocking, the introduction of JS blocking page rendering, JS does not block the loading of resources, JS sequential execution, blocking the subsequent execution of JS logic.

Image compression and splicingWeb front end performance optimization principle

Differences between PNG, png-8, png-24 and JPEG format pictures

PNG format is suitable for situations where transparency is required. Png-8 cannot handle gradients in complex color gamut, and png-24 can retain gradients almost without distortion

Image compression methodWeb front end performance optimization principle

Using Photoshop’s own image compression, file storage as the format used by the web, in general, JPEG selection output quality of 70-80% can ensure almost no visual difference.

Page volume

Volume compression ratio of files before and after optimization = volume after optimization ÷ volume before optimization

Web front end performance optimization principle

Lazy loading principleWeb front end performance optimization principle

The definition of lazy loading is that for pictures, picture resources are many for mall project pictures, and the business scenario with a long page is applicable to reduce the loading of invalid resources. Too many resources loaded concurrently will block the loading of JS.

When the image enters our visual area, request to load resources

Effect of lazy loading delay loading

PreloadingprincipleWeb front end performance optimization principle

Static resources such as pictures are requested in advance before use. Resources are loaded from the cache when they are used to improve the user experience.

What is the mechanism of redrawing and reflow?Web front end performance optimization principle

Frequent redraws and reflows can cause the UI to render frequently, resulting in slower JavaScript. Reflow: when a part of the render tree needs to be rebuilt due to the change of the size and layout of the elements, reflow and redraw will be triggered. When some elements of the render tree need to modify the attributes, which do not affect the appearance, style and layout of the elements, it is called redraw, such as modifying the color.

So reflow must cause redrawing, but redrawing does not necessarily cause reflow.

Master some CSS attributesWeb front end performance optimization principle

Web front end performance optimization principle

The elements of frequent redraw reflow are separated as an independent layer, so the redraw reflow of this element can only affect this layer.

Separate an element into separate layers, using CSS attributes

Avoid using CSS attributes that trigger redraws, reflows, and redraws can be separated from reflows very often.

Browser storageWeb front end performance optimization principle

Learn about localstorage, cookies, sessionstorage, indexdb

Understand the application of PWA and service worker

Multiple browser storage modes coexist

What is a cookieWeb front end performance optimization principle

Cookie is used to pass relevant information to the server, and let the server distinguish which client is currently requesting. Cookie was existed in 1993. Its purpose is to distinguish HTTP requests. Originally, HTTP requests are stateless, that is, the connection after the request is closed, and cookie is to maintain the state of the client.

It is used for the interaction between browser and server and the storage of client’s own data.

There are restrictions on cookies. As a browser, the size of cookies is about 4KB, and the expiration time needs to be set.

The cookie generation method is set cookie of HTTP response header. The cookie can be read and written through document.cookie. The traffic loss of CDN under the relevant domain name in the cookie is httponly.

LocalStorageWeb front end performance optimization principle

It is specially used for browser storage, with a size of about 5m, well encapsulated interface and local cache, which can improve the loading speed of the first screen.

SessionStorageWeb front end performance optimization principle

Session level browser storage, about 5m in size, is used on the client side, does not communicate with the server side, and the interface encapsulation is better.

What is PWA?Web front end performance optimization principle

It is a new model of web app, not a kind of cutting-edge technology, but a kind of progressive web app through a series of new web features. PWA can also provide basic page access in the environment without network. Web app without network can not receive the display of basic page, but PWA will not show the page without connecting to the network. It is very fast. It can render web pages and access network data very quickly. It can be added to mobile desktop.

What is service workerWeb front end performance optimization principle

It is a script, the browser is independent of the current page, it will run in the background, to achieve some independent pages. It has the characteristics of intercepting and processing network requests.

Cache policyWeb front end performance optimization principle

Cache, DNS cache, CDN deployment and cache, HTTP cache

Learn about cache control, last modified, Etag. Httpheader attributes, cache control attributes, Max age, s-maxage, private, public, no cache, no store.

The browser will consume a certain amount of time in DNS resolution. For some high traffic users, it is necessary to do a good job in DNS caching, CDN caching, CDN distribution as a static resource file, and do a good job in static resource caching, so as to speed up the loading speed of the website,

Move to optimization, use cache, reduce redirection, optimize the first screen, ensure that the first screen loading data is less than 14KB, and do not abuse the web font.

Server performance optimizationWeb front end performance optimization principle

The server is node.js, so it can also be optimized.

Web front end performance optimization principle

Web front end performance optimization principle

Google’s pagespeed team’s test shows that 30-50kb (compressed) is the appropriate size range for each JavaScript file: it can reduce the network delay caused by small files, and ensure incremental and hierarchical execution. –Authoritative guide to Web Performance

Web front end performance optimization principle

Reduce HTTP requests, merge JS files, merge CSS files, use CSS Sprite, use Base64 to represent simple pictures.

Mobile terminal optimization, long list rolling optimization, function anti shake and function throttling. Use touchstart and touchend instead of click and HTML’s viewport settings to enable GPU rendering acceleration.

Web front end performance optimization principle

On the essence and method of web front end optimizationWeb front end performance optimization principle

1、 Reduce too many HTTP external requests

2、 Use CSS in the right place

3、 Optimize code

Reference link

Recommended reading click the title to jump

[interview Vue family bucket] the syntax structure of the front-end interaction mode of vue-es7? Async/await

[interview needs – Vue family bucket] I’ll show you the front-end route of Vue

[interview needs] master the principle of this, call and apply in JavaScript

Every day in 2019, I just wait for her to appear, spend the rest of my life, celebrate more than one year’s gold digging annual essay

Coming in is a family [dada front end technology community ⑥]

Think this article will help you? Please share with more people

Pay attention to “dada front end” and add stars to improve front end skills

In the blog platform, there is still a long way to go in the future. I also hope that you can support and criticize your articles in the future. We can make progress together and take a long way together.

Thank you very much for reading here. If this article is well written, I thinkDada“If I have something, I think I can keep learning and make friends with himPlease like it, please pay attention to it, please share it, it’s true for me

Very useful!

Thanks for reading. It’s not easy to be original. Just order one if you like[Look at] or [Forwarding circle of friends], which is the biggest driving force of my writing.

Feedback

If the content of this number is not in place (for example, involving copyright or other issues), please contact us in time for rectification, and we will deal with it as soon as possible.

This is a public with a quality and attitude.

Focus, good luck

Web front end performance optimization principle

Good article, I’m reading it

Recommended Today

PHP realizes UnionPay business H5 payment

UnionPay business H5 payment interface document: document address 1: H5 payment interface address: 1: Alipay payment Test address: http://58.247.0.18:29015/v1/netpay/trade/h5-pay Official address: https://api-mop.chinaums.com/ 2: UnionPay payment Test address: http://58.247.0.18:29015/v1/netpay/uac/order Official address: https://api-mop.chinaums.com/ 2: Basic parameters required by the interface The interface uses get parameters. After the interface parameters are directly put into the interface address, the […]