In the previous development, I often came into contact with the problem of front-end performance optimization. During this period of time, I read a series of courses and blogs of big wigs. Here is a summary of front-end performance optimization.

A, directories,

  • Based optimization
    • Front-end optimization principle analysis
    • HTML optimization
    • CSS optimization
    • Js optimization
    • Image optimization
    • File merge optimization
  • Advanced optimization
    • Lazy file loading and preloading
    • Redraw and reflow
    • Browser cache
    • Browser Cache policy

Second, basic optimization

1. Front-end optimization principle analysis

Question 1: What happens to a request from the time it is sent to the time it is returned?

The user enters a URL into the browser, and the core code in the browser splits and parses the URL. The browser will send the domain to the DNS server, and the DNS server will query the corresponding IP address according to the domain, and return the IP address to the browser. After the browser has the IP address, it will know the address to send the request, and follow the protocol, type the IP address into the protocol, and carry the parameters related to the request. After the request is sent to our network, through LAN, switch, router and trunk network, the request will arrive at our server, which is MVC architecture. The request will first enter controller, which will distribute relevant logic, and call model layer, which interacts with data. In data interaction, take the data from the database, and finally distribute the rendered data to the network through the View layer. The RESPONSE of the HTTP request is returned to the browser from the server, and the browser begins to render.

Potential performance optimization points:

  • 1. DNS cache
  • 2. Reduce HTTP requests
  • 3. Reduce the size of HTTP requests
  • 4. Take the nearest network request when making a network request
  • 5. Browser-side cache

Q2: How does a web site render on the browser side?

Here’s a detailed description of the image above:

This HTML document will be parsed by the HTML parse in the browser. The tag will be parsed into tokens through the lexical analysis process, and the tokens will be parsed from top to bottom in the HTML document. Because it is constantly parsed from top to bottom by using the next token, in the process of lexical analysis, tags like Link Script can be correspondingly parsed, and the corresponding Web resources in such tags will be further requested by the browser to the network. The requested JavaScript Web resource is handed over to the V8 JavaScript execution engine in the browser for execution. Css-related resource requests come back and the browser generates the corresponding CSSOM tree. The premise of the page rendering is to generate the Render tree once the DOM tree and CSSOM tree are in place, to make a further layout for the rendering.

Summary from the above two questions we can see that the core of front-end performance optimization is to reduce HTTP requests and reduce the size of HTTP requests.

2. HTML optimization

  • The principle of
  • implementation

Principles of compression include Spaces, tabs, line breaks, etc., as well as some other meaningful characters, such as HTML comments, can also be compressed.

Gulp using gulp-HTMLmin plug-in for compression 2. Online compression software for compression (not applicable to large projects)

gulp.task('htmlmin'.function() {
   	var options = {
   		removeComments: true// Clear HTML comment collapseWhitespace:true, / / compress HTML collapseBooleanAttributes:true// omit the value of the Boolean attribute <input checked="true"/> ==> <input />
   		removeEmptyAttributes: true, // remove all Spaces as attribute values <input id="" /> ==> <input />
   		removeScriptTypeAttributes: true// Delete <script>type="text/javascript"
   		removeStyleLinkTypeAttributes: true// Delete <style> and <link>type="text/css"
   		minifyJS: true// Compress the page JS minifyCSS:true// compress the page CSS}; var htmlSrc ='./src/*.html',
   		htmlDst = './dist'; gulp.src(htmlSrc) .pipe(htmlmin(options)) .pipe(gulp.dest(htmlDst)); // HTML of the same name will be replaced directly with});Copy the code

3. CSS optimization

  • The principle of
  • implementation

Principle invalid code deletion, space deletion, TAB deletion

Gulp: gulp-minify- CSS: gulp-minify- CSS: gulp-minify- CSS: gulp-minify

4. JS optimization

  • The principle of
  • implementation

Principle Deletion of invalid characters, deletion of comments, reduction and optimization of code semantics, code protection (change some semantically named names to A/B/C, etc.)

2. Online compression software for compression (not applicable to large projects)

5. Image optimization

Image type

  • JPG Lossy compression High compression rate does not support transparency
  • PNG supports transparent browsers with good compatibility
  • Webp compression is better and has compatibility issues with iOS WebView
  • SVG vector images are scenes with relatively simple image styles

The solution

  • Image Inline (reduces the number of HTTP requests)
  • Sprite diagram (reduce the number of HTTP requests)

Implementation method

  • Online image compression software
  • Gulp image compression plugin for Gulp-Imagemin

6. File merging and optimization

Existing problems

  • First screen rendering problem (one HTTP request is too large and takes too long due to multiple file merging)
  • Cache invalidation issues (changes to any of the files after the merge will invalidate the cache)

The solution

  • Common library merge
  • Merging of different pages

Implementation method

Use gulp’s gulp-concat plugin to merge files.

Third, advanced optimization

1. Lazy file loading and preloading

Lazy loading

  • Request the image resource after the image enters the viewable area
  • It is suitable for e-commerce and other business scenarios with many pictures and long pages
  • Reduce the loading of invalid resources
  • Too many concurrent loading resources will block JS loading, affecting the normal use of the website

preload

  • Advance requests for static resources such as images before they are used
  • Resources can be loaded from the cache when used, improving the user experience
  • Page display dependency maintenance

Lazy loading implementation method HTML code

<! doctype html> <html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>lazyload</title>
	<link rel="stylesheet" href="main.css" />
</head>
<body>
	<div class="image-list">
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i3/3851834739/TB2KAmyBHGYBuNjy0FoXXciBFXa_!! 3851834739.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i3/3851834739/TB2RYRxqeGSBuNjSspbXXciipXa_!! 3851834739-0-item_pic.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/bao/uploaded/i3/1210506068553231586/TB2ZL6qt3RkpuFjy1zeXXc.6FXa_!! 0-saturn_solar.jpg_240x240xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i2/511076404/TB2J7wUApmWBuNjSspdXXbugXXa_!! 511076404.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/bao/uploaded/i3/23745640/TB2zBv9D1uSBuNjy1XcXXcYjFXa_!! 0-saturn_solar.jpg_240x240xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i3/587488716/TB2OyN5wrSYBuNjSspiXXXNzpXa_!! 587488716.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/bao/uploaded/i1/114335006/TB2IewMr41YBuNjy1zcXXbNcXXa_!! 0-saturn_solar.jpg_240x240xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i4/2782657655/TB2VvzUfYorBKNjSZFjXXc_SpXa_!! 2782657655.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/bao/uploaded/i3/13016599/TB2TuxpuGSWBuNjSsrbXXa0mVXa_!! 0-saturn_solar.jpg_240x240xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i2/90919986/TB2KqfVxv9TBuNjy1zbXXXpepXa_!! 90919986.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/bao/uploaded/i4/52863407/TB2mKqZDkKWBuNjy1zjXXcOypXa_!! 0-saturn_solar.jpg_240x240xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i3/1969607927/TB25oQdaIuYBuNkSmRyXXcA3pXa_!! 1969607927.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/bao/uploaded/i2/31490775/TB26MyDb8smBKNjSZFsXXaXSVXa_!! 0-saturn_solar.jpg_240x240xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i1/886644258/TB29ufKvrxmpuFjSZJiXXXauVXa_!! 886644258.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i2/886644258/TB2D9pNwSxjpuFjSszeXXaeMVXa_!! 886644258.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/bao/uploaded/i2/121453312/TB2iATKD29TBuNjy0FcXXbeiFXa_!! 0-saturn_solar.jpg_240x240xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i4/3083173120/TB2CCLWDr5YBuNjSspoXXbeNFXa_!! 3083173120.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/bao/uploaded/i4/15303864/TB2eVxzhYsrBKNjSZFpXXcXhFXa_!! 0-saturn_solar.jpg_240x240xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i2/694223667/TB2N4cXy1ySBuNjy1zdXXXPxFXa_!! 694223667.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i4/73861778/TB2r8vgl4uTBuNkHFNRXXc9qpXa_!! 73861778.jpg_100x100xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/bao/uploaded/i2/26868233/TB2j2jQAhSYBuNjSsphXXbGvVXa_!! 0-saturn_solar.jpg_240x240xzq75.jpg" />
		<img src="" class="image-item" lazyload="true" data-original="https://gma.alicdn.com/i3/694223667/TB21ohCqOCYBuNkHFCcXXcHtVXa_!! 694223667.jpg_100x100xzq75.jpg" />
	</div>
	
	<script type="text/javascript" src="lazyload.js"></script>
</body>
</html>
Copy the code

CSS

.image-item{
	width: 40%;
	margin-right: 5%;
	display: inline-block;
	height: 400px;
	background: gray;
}

.image-list{
	margin-left: 5%;
}
Copy the code

JS

/ * * * principle need to compare the height of the viewing area and the current image in the area of the top value to determine whether the loading picture * Element. The getBoundingClientRect () method returns the Element size and its position relative to the viewport. * * the dataset is used to retrieve a property value * * / var viewHeight = document. The documentElement. ClientHeight;function lazyload(){
	var eles = document.querySelectorAll('img[data-original][lazyload]');
	Array.prototype.forEach.call(eles,function(item,index){
		var rect;
		if(item.dataset.original === ' ')
			return;
		rect = item.getBoundingClientRect();
		if(rect.bottom >=0 && rect.top < viewHeight){
			!function(){
				var img = new Image();
				img.src = item.dataset.original;
				img.onload = function(){
					item.src= img.src;
				}
				item.removeAttribute('data-original');
				item.removeAttribute('lazyload');
			}()
		}
	})
}

lazyload();

document.addEventListener('scroll', lazyload);
Copy the code

The preloading implementation method

Img tag + display:none <img SRC =".. /a.png" style="display:none;" />

new Image()
var img =new Image();
img.src="sdsds.png";
Copy the code

2. Redraw and reflow

  • The problem
  • Browser redraw and backflow mechanisms
  • What is redraw
  • What is reflux
  • What operations can produce redraw and reflux?

Question 1: Does CSS performance slow JavaScript down? (would)

CSS and JavaScript block each other (JavaScript may fetch relevant render results in code) one thread => JavaScript parses one thread => UI render

==== All these two threads are mutually exclusive ====

The reasons for the relationship between front-end performance optimization and redraw and backflow are as follows: Frequent triggering of redraw and backflow will lead to frequent UI rendering, which will eventually slow down JS and deteriorate page performance.

Backflow changes in size, layout, hiding, and so on that require reconstruction are called backflow.

Triggers for backflow:

  • Box model related properties
  • Locate and float related properties
  • Node internal text structure

Repainting appearance, style changes without affecting the layout need to be repainted

3. Browser cache

  • cookie
  • localstroage sessionstorage
  • Service Workers

4, caching,

  • cache-control
  • expires
  • last-modified
  • etag