(add stars to the front end of dada to improve the front end skills)
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 optimization
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 interviewer
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.
Front end performance optimization, resource merging and compression
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?
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.
In the process from browser to server, which processes can be optimized for our front-end?
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 resources
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.
The first is to use online website compression, HTML minifier tool for compression, and backend template engine for rendering compression.
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 JS
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 documents
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 resources
Practical page development, website compression and merging, FIS automatic compression and merging.
The construction of front-end automation realizes compression and merging
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
After compression, the performance before and after optimization should be better, and the large resource effect is obvious
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 optimization
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 splicing
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 method
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.
Volume compression ratio of files before and after optimization = volume after optimization ÷ volume before optimization
Lazy loading 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
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?
So reflow must cause redrawing, but redrawing does not necessarily cause reflow.
Master some CSS attributes
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.
Learn about localstorage, cookies, sessionstorage, indexdb
Understand the application of PWA and service worker
Multiple browser storage modes coexist
What is a cookie
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.
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.
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?
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 worker
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, 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 optimization
The server is node.js, so it can also be optimized.
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.
On the essence and method of web front end optimization
1、 Reduce too many HTTP external requests
2、 Use CSS in the right place
3、 Optimize code
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
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
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.
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
Good article, I’m reading it