Question:
- How often have you been told by product or QA that your page is slow to open?
- Have you ever opened a page on your phone and found it stuck?
.
If you encounter these problems, you are not optimizing your page well enough. This article will look at front-end performance optimization from a macro perspective to make sure you have a holistic approach to the problem.
Let’s start with a classic interview question
Q: What happens when the user enters a web address in the browser and sees the entire page?
This question covers the whole process of the Internet, and only when you understand this process can you understand what we can do as front-end engineers.
What happens when you type in the url?
- The user will enter www.baidu.com
- The browser uses DNS to parse the URL into IP
- Establish A TCP link with the IP address and send an HTTP request (three handshakes, four waves)
- The server accepts the request, checks the library, reads and writes the file, and returns an HTTP response
- The browser receives the HTML and starts rendering line by line, generating a DOM tree.
- Then render the CSS into cssOM.
- Dom Tree is merged with cssOM to become render Tree.
- Generate the page by reflux, return.
- Load js and execute JS.
The browser executes js with a single thread + task queue.
Many people like to say that browsers are single threaded + event queues. This is not true. When we open the browser, the operating system actually starts a process for us, and the tabs open in the browser are like threads. So js runs in threads. 支那
Optimal point
Optimization is basically divided into two directions:
- It’s important to load fewer files
- File packing compression
- Image format and compression
- The cache
- CDN reduces distance and improves loading speed and efficiency
- SRR Execution sequence of home page files
- Lazy – load lazy loading
- Execute less code
- The browser is good enough that most of the optimization strategies are concentrated within vue and React
- Long list (memory optimized)
1. Some mobile terminal models, such as Taobao home page infinite scrolling, if direct rendering 1. 1. How to display a list of items with a length of 10000Copy the code
I will list below, which points can be optimized. 支那
DNS cache
Optimization: Prefetch prefetch, such as using CDN domain names.
<link rel="dns-prefetch" href="//domain.com">
Copy the code
This is the DNS cache conducted by Taobao.
TCP and UDP are compared
Internet protocol is about making machines talk
- Know who the target is? The IP protocol is responsible for addressing.
- TCP protocol is based on IP protocol, responsible for the integrity and order of data, like express companies
A. Three-way handshake b. Resend, sliding window, packet sticking, and slow start c. TCP This protocol is provided by the operating system
- HTTP is responsible for the application layer based on TCP
A. Header and body
- UDP is also based on IP, sending and receiving directly, whether data is lost or not
A. What scenarios is UDP suitable for? B. Good performance C. Suitable for high performance requirements, but do not care about the occasional loss of frame scene, the package is small enough, no subcontracting I. Iii: DNS(packet small enough)
What is a sticky bag?
TCP has a data buffering strategy, if you can glue the packets that are close to each other into one packet.
Use the browser’s caching mechanism
Above is an overview of the browser cache, which can be configured according to the browser cache policy. For details, see:What is the browser caching mechanism?
Internal principle of CDN
CDN is to deploy our pictures to various computer rooms (Beijing, Shanghai, Hangzhou,…..) When the user visits, return the address of your most recent image.
Image optimization
Images usually occupy the most traffic. The average image size loaded by PC is 600K, which is even larger than the js package file. Therefore, the optimization of images is also a good benefit
-
jpg
-
Lossy compression
-
Small volume does not support transparency 3. Used for background, round play
-
png
-
png
-
Lossless compression, high quality, support transparency
-
More colorful lines, small pictures, such as logo, commodity icon
-
svg
-
Text, volume small vector diagram
-
Rendering cost, learning cost
Sprite Image packaging reduces the number of HTTP requests webpack-Spritesmith
Lazy image loading
Image lazy loading means the user is trying to load inside the image. Images that do not appear in the attempt do not load. How to load images lazily
gzip
Accept-encoding: gzip Enables gzi
All of these are strategic and configuration items to optimize the front end, so let’s look at how to optimize the code we write. 支那
Code performance killers: backflow (rearrangement) and redraw
** Reflux (reorder) : When visible DOM is added or removed, the position of the element changes, the size of the element changes, and the content changes. (e.g. the text changes or the image is replaced by another image of a different size); This is inevitable when the page is first rendered. Because backflow calculates the position and size of elements based on viewport size, window size changes are bound to cause backflow. Redraw: When the page element style change does not affect the location of the element in the document flow (such as background-color, border-color, visibility), the browser only assigns the new style to the element and redraws it.
When does reflux trigger when you use a property like this: OffsetTop, offsetLeft, ScrollLeft, scrollHeight, clientTop, clientLeft, clientWidth, clientHeight, Pay attention! What does a property like this look like? These values have one thing in common: they need to be calculated in real time. So the browser will also backflow in order to get these values.
Note: backflow must be redrawn, and redrawn does not necessarily backflow. If the code is constantly reflow and redrawn, the performance of the page will definitely degrade.
Several ways to reduce redrawing and reflux
1.Separate read and write operations
div.style.left = '10px';
div.style.top = '10px';
div.style.width = '20px';
div.style.height = '20px';
console.log(div.offsetLeft);
console.log(div.offsetTop);
console.log(div.offsetWidth);
console.log(div.offsetHeight); So it just happens1Div.style.left ='10px';
console.log(div.offsetLeft);
div.style.top = '10px';
console.log(div.offsetTop);
div.style.width = '20px';
console.log(div.offsetWidth);
div.style.height = '20px';
console.log(div.offsetHeight); The trigger4timeCopy the code
2. Several style changes
div.style.left = '10px';
div.style.top = '10px';
div.style.width = '20px';
div.style.height = '20px'; Although modern browsers have an optimization mechanism for rendering queues, antique browsers are still inefficient4Even then, we can still make the optimization we need the cssText property to merge all the style changes to div.style.csstext ='left:10px; top:10px; width:20px; height:20px; '; This only requires the DOM to be modified once and the processing only triggers1It's a little bit cleaner and it's only one line of code, but one thing to be aware of is that cssText overwrites the existing interline style and if you want to keep the original interline style, do this div.style.csstext +='; left:10px; '; In addition to cssText, we can also modifyclassClass name to make style changesdiv.className = 'new-class'; This approach is maintainable and also helps us get rid of the display code (which has a slight performance impact, and changes)classYou need to check the cascading style, but that doesn't outweigh the flaws.)Copy the code
3. Cache layout information
div.style.left = div.offsetLeft + 1 + 'px';
div.style.top = div.offsetTop + 1 + 'px'; This is caused by a read operation followed by a write operation2The secondary reorder cache can be optimizedvar curLeft = div.offsetLeft;
var curTop = div.offsetTop;
div.style.left = curLeft + 1 + 'px';
div.style.top = curTop + 1 + 'px'; This is also equivalent to separating read and write operations optimized to1Time to reorderCopy the code
4. Modify elements in batches
var ul = document.getElementById('demo');
var frg = document.createDocumentFragment();
for(var i = 0; i < 5; i++){
var li = document.createElement('li');
var text = document.createTextNode(i);
li.appendChild(text);
frg.appendChild(li);
}
Copy the code
5. (Away from the document flow)
The animation is applied to elements whose position attribute is Absolute or fixed
6. Css3 Hardware Acceleration (GPU acceleration)
Instead of thinking about how to reduce backflow and redraw, we’d rather not backflow and redraw at all: tansform\option\filters… These properties trigger hardware acceleration and do not cause reflux or redraw. Cons: Possible potholes: Excessive use can take up a lot of memory and performance, sometimes causing problems such as blurring fonts.
Other:
Best practices for front-end deployment (caching)
How best to use the cache
- HTML nocache
- Add fingerprint to the file and change the file name xx.dd33.js
- Static resources are in the CDN specific CDN domain name
- The CDN shortens the distance between the user and the server and improves efficiency
- Browsers have a limit on the number of concurrent accesses to a domain name, so CDN domain names are used exclusively to load static resources.
- HTML and JS CSS should be separated
- Go ahead and take one
- If you use the old JS cache, you will hear an error
- If the js cache is invalid, the old HTML is loaded with the new JS
- Js generates a new file because the content is modified
- Online static resource (cache setting takes a long time, there are changes, it is a new file)
- HTML on (no strong cache set)
Function closure and anti – shaking
/ / the closure
const throtter = (func,wait=100) = >{
let lastTime = 0;
return (. args) = >{
let now = new Date(a);if(now-lastTime>wait){
lastTime = new;
func.apply(this,args)
}
}
}
const debounce = (func,wait=100) = >{
let timer = 0;
return (. args) = >{
if(timer){
clearTimeout(timer);
}
timer = setTimeout(() = >{
func.apply(this,args)
},wait)
}
}
Copy the code
vue-virtual-scroller
Skeleton screen
npm install vue-skeleton-webpack-plugin