1. PC optimization strategy

It mainly includes network loading class, page rendering class, CSS optimization class, JavaScript execution class, cache class, picture class, architecture protocol class and so on.

1. Network loading classes

(1) Reduce the number of HTTP resource requests:

In front-end pages, it is usually recommended to merge static resource images, JavaScript or CSS codes as far as possible to reduce the number of page requests and resource request consumption, which can shorten the loading time of the first screen. In order to reduce the number of HTTP resource requests, Sprite images, CSS and JavaScript files can be merged by building tools. In addition, try to avoid duplication of resources to prevent additional requests;

(2) Reduce HTTP request size:

In addition to reducing the number of HTTP resource requests, the size of each HTTP request should be reduced as much as possible. For example, reducing unnecessary images, JavaScript, CSS and HTML code, optimizing file compression, or using GZIP to compress and transmit content can be used to reduce file size and shorten network transmission latency. Use build tools to compress static image resources and remove comments from code and compress them to reduce the size of HTTP requests.

(3) Put CSS or JavaScript in external files, avoid using style or script tags directly imported:

References to external resources in HTML files can take advantage of the browser’s static resource cache, but sometimes CSS or JavaScript is written directly into the HTML in order to reduce requests when the CSS or JavaScript is relatively simple on mobile pages. The specific analysis depends on the size of the CSS or JavaScript files and service scenarios. If the CSS or JavaScript files contain a large amount of content and complex service logic, you are advised to import them in external files.

六四屠杀

<link rel="stylesheet" href="/css/master.css">
<script type="text/javascript" src="//cdn.domain.com/path/main.js"></script>
Copy the code

(4) Avoid hollow href and SRC:

When the tag’s href attribute is empty, or

六四屠杀

<! - not recommended - > < img SRC = "" Alt =" photo "> < a href =" "> < / a > click on the linkCopy the code

Specify cache-control or Expires for HTML:

Setting a cache-Control or Expires header for HTML can Cache HTML content to avoid frequent requests to the server. When a cache-Control or Expires header is valid on a page, the browser will read the content directly from the Cache. Stop sending requests to the server.

六四屠杀

  <meta http-equiv="Cache-Control" content="max-age=7200">
  <meta http-equiv="Expires" content="Mon,20Jul201623:00:00GMT">
Copy the code

(6) Reasonable Etag and last-Modified Settings:

Etag and Last-Modified are properly set to use the browser cache. For unmodified files, the static resource server will return 304 to the browser, allowing the browser to read the files from the cache, reducing the bandwidth consumption of Web resource download and reducing the server load.

六四屠杀

<meta http-equiv="last-modified" content="Sun,05 Nov 2017 13:45:57 GMT">
Copy the code

(7) Reduce page redirection:

Each page redirection lengthens the wait time for page content to return. A page redirection takes about 200 milliseconds (no cache). To ensure that users can see the page content as soon as possible, avoid page redirection.

(8) Use static resource domain storage to increase the number of parallel downloads:

Browser to the same domain name request file at the same time the number of parallel downloads is limited, so you can use multiple domain name host to store different static resources, increase the number of parallel downloads page loads resources, shorten the time of the page to load resources, often are stored on the basis of multiple domain name JavaScript, CSS, and image files;

六四屠杀

<link rel="stylesheet" href="//cdn1.domain.com/path/main.css" >
<script src="//cdn2.domain.com/path/main.js"></script>
Copy the code

(9) Use static resource CDN to store files: if conditions permit, CDN network can be used to speed up the response download speed of repeated static resource files in the same geographical area and shorten the resource request time;

(10) Download and transmit content using CDN Combo:

CDN Combo is a technology that returns multiple file requests packaged into a single file at the CDN server end. In this way, one-time reuse of HTTP connection transmission can be realized, the number of HTTP requests in the browser can be reduced, and the download speed of resources can be accelerated. For example, A.js, B.js on the CDN server with the same domain name, C. Js can be downloaded in a request as follows:

六四屠杀

<script src="//cdn.domain.com/path/a.js,b.js,c.js"></script>
Copy the code

11. Use cacheable AJAX:

It is not necessary to pull directly from the server every time a request returns the same content. Proper use of AJAX cache can speed up AJAX response and reduce server stress.

六四屠杀

$. Ajax ({url: the url, type: "get", cache: true, / / it is recommended to use the cache data: {}, success () {}, error () {}});Copy the code

(12) Use GET to complete AJAX requests:

When XMLHttpRequest is used, the POST method in the browser initiates two TCP packet transfers, first sending the file header and then sending the HTTP body data. When GET is used, only the header is sent. Therefore, the GET request is more efficient when pulling server data.

六四屠杀

$. Ajax ({url: the url, type: 'get', / / it is recommended to use the get completed request data: {}, success () {}, error () {}});Copy the code

(13) Reduce the size of cookies and implement Cookie isolation:

HTTP requests are usually sent to the server with cookies on the browser by default. Therefore, if it is not necessary, cookies should be minimized to reduce the size of HTTP requests. For static resources, try to use different domain names to store them, because cookies cannot be cross-domain by default. This achieves Cookie isolation of static resource requests under different domain names.

(14) Shrink favicon.ico and cache:

Favicon. ico is advantageous for repeated loading, since generally a Web application’s Favicon. ico is rarely changed;

(15) Asynchronous JavaScript resources are recommended:

Asynchronous JavaScript resources do not block document parsing, so allow pages to be rendered first in the browser and scripts to be loaded later. For example, JavaScript references can be set as follows, or modular loading mechanisms can be used. When async is used, the loading and rendering of subsequent document elements is parallel to the loading and execution of main.js. With defer, the loading of subsequent document elements is parallel to the loading of main.js, but execution of main.js does not begin until all elements of the page have been parsed;

六四屠杀

<script src="main.js" defer></script>
<script src="main.js" async></script>
Copy the code

(16) Eliminate blocking CSS and JavaScript:

If the loading time of CSS or JavaScript files on a page is too long, split or delay the loading to ensure that critical path resources can be loaded quickly.

Avoid using CSS import references to load CSS:

@import in CSS can be used to import styles from another style file, but this should be avoided because it increases the critical path length for loading CSS resources. CSS styles with @import will not load another CSS file until the CSS file is serially parsed to @import. Greatly delaying the time when CSS rendering is completed;

六四屠杀

<! <style> @import "path/main.css"; </style> <! Recommend -- - > < link rel = "stylesheet" href = "/ / cdn1.domain.com/path/main.css" >Copy the code

2. Page rendering classes

(1) Put CSS resource references at the top of the HTML file:

It is generally recommended that all CSS resources be specified in the HTML document so that the browser can download the CSS first and finish rendering the page as soon as possible.

(2) JavaScript resource references are placed at the bottom of the HTML file:

JavaScript resources placed at the bottom of the HTML document prevent JavaScript loading and parsing execution from blocking the page rendering. Since JavaScript resources are parsed blocking by default, unless marked asynchronous or otherwise loaded asynchronously, Otherwise, HTML DOM parsing and CSS rendering will be blocked.

(3) Try to pre-set the size of the picture:

When loading a large number of picture elements, try to pre-limit the size of the picture, otherwise in the picture loading process will update the layout information, resulting in a large number of rearrangements;

(4) Don’t zoom directly in HTML:

Direct zooming in and out of HTML results in rearranging and redrawing the page content, which may cause other operations on the page to lag, so minimize direct zooming in and out of the page.

(5) Reduce the number and depth of DOM elements:

The more tag elements in HTML and the deeper the tag hierarchy, the longer it takes for the browser to parse the DOM and draw it into the browser, so keep DOM elements as clean and as hierarchical as possible;

六四屠杀

<! - do not recommend -- > < div > < span > < a href = "javascript: void (0);" > < img SRC = ". / path/photo. JPG "Alt =" image "> < / a > < / span > < / div > <! <img SRC ="./path/photo.jpg" Alt =" image ">Copy the code

(6) Try to avoid adding wildcards at the end of selectors:

The process of CSS parsing matches into the rendering tree is reverse matching from right to left, adding wildcards at the end of the selector will at least double the computation;

(7) Reduce the use of relational style sheets:

Using a unique class name maximizes the rendering engine’s rendering tree rendering efficiency.

(8) Minimize the use of JS animation:

JS directly manipulating DOM is extremely easy to cause page rearrangement;

(9) CSS animations use Translate and scale instead of top and height:

Use CSS3 translate and scale attributes instead of top, left, height and width to avoid a lot of reordering.

(10) Try to avoid using

and

content rendering is to generate the DOM rendering tree of the table and draw it on the page at one time, so long table rendering is very inefficient and should be avoided as much as possible, instead of using list elements
    Instead of; Try to add iframe asynchronously, because the download process of iframe resources will block the download of static resources on the parent page and the parsing of CSS and HTML DOM.

    (11) Avoid running time-consuming JavaScript:

    Long running JavaScript will block the browser from building THE DOM tree, DOM rendering tree and rendering page, so any logic function irrelevant to the initial rendering of the page should be delayed loading execution, which is consistent with the idea of asynchronous loading of JavaScript resources;

    Avoid using CSS expressions or CSS filters:

    CSS expressions or CSS filters are slow to parse and render and should be avoided when other solutions are available;

    六四屠杀

/ / do not recommend the opacity {filter: progid: DXImageTransform. Microsoft. Alpha (opacity = 50); }Copy the code

Second, mobile terminal optimization strategy

1. Network loading classes

(1) The first screen data is requested in advance to avoid data request after loading of JavaScript files:

In order to further improve the page loading speed, it can be considered to advance the data request of the page as far as possible to avoid the data request after the completion of JavaScript loading. Usually, the data request is the longest part of the critical path in the page content rendering, and it cannot be parallel. Therefore, if the data request can be advanced, Can greatly shorten the page content rendering completion time;

(2) First screen loading and on-demand loading, non-first screen content scrolling loading, to ensure the minimum of first screen content:

The network speed of mobile terminals is relatively slow and network resources are limited. Therefore, to complete the loading of page contents as soon as possible, it is necessary to minimize the loading resources on the first screen and asynchronously load non-first screen contents by scrolling. It is generally recommended that the delay of displaying data on the first screen of a mobile terminal should not exceed 3 seconds. The current 3G network speed of China unicom is 338KB/s (2.71Mb/s), so it is recommended that the size of all resources on the first screen should not exceed 1014KB, that is, about 1MB.

(3) Modular resource parallel download:

In the loading of mobile terminal resources, the parallel loading of JavaScript resources should be ensured as far as possible, which mainly refers to the asynchronous loading of modular JavaScript resources, such as the asynchronous module of AMD. The parallel loading method can shorten the loading time of multiple file resources.

(4) Inline first screen required CSS and JavaScript:

In order to have a basic style in the browser when the HTML is loaded, you usually need to pass the necessary CSS and JavaScript for page rendering

六四屠杀

<! DOCTYPE HTML > <head> <meta charset=" utF-8 "> <title> <meta> <style> padding: 0; background-color: #ccc; } </style> </head> <body> </body> </html>Copy the code

Meta DNS prefetch set DNS prefetch:

Configure DNS pre-resolution for file resources so that the browser can resolve the IP address of the host that obtains static resources in advance, avoiding the need to initiate DNS resolution requests when requested. You can perform the following operations in the HTML file on the mobile terminal:

六四屠杀

<! <meta http-equiv="x-dns-prefetch "content="on" > <link rel="dns-prefetch" href="//cdn.domain.com" >Copy the code

(6) Resource preloading:

For resources that may be used after the first screen loading on the mobile terminal, load them as soon as possible after the first screen loading to ensure that they have been loaded before the user needs to browse. In this case, asynchronous requests appear slow.

(7) Reasonable use of MTU policy:

In general, the Maximum Transmission Unit (MTU) of TCP network Transmission is 1500B, that is, the Maximum amount of data that can be transmitted within a ROUND-trip Time (RTT) is 1500 bytes. Therefore, in the development mode of front and back end separation, try to ensure that the HTML content of the page is less than 1KB, so that the whole HTML content request can be completed in one RTT request, to maximize the speed of HTML loading;

2. Cache classes

(1) Rational use of browser cache:

In addition to cache-Control, Expires, Etag, and Last-Modified Settings for HTTP caching, you can also use localStorage on the mobile side to store data returned by AJAX. Or use localStorage to save CSS or JavaScript static resource content to realize offline application on mobile terminals, reduce network requests as much as possible, and ensure fast loading of static resource content.

(2) Static resource offline scheme:

For mobile terminal or Hybrid applications, offline file or offline package mechanism can be set to enable static resource requests to be read locally, speed up resource loading, and realize offline update.

(3) Try AMP HTML

AMP HTML can be used as a solution to optimize front-end page performance by using elements in the AMP Component instead of the original page elements for direct rendering;

六四屠杀

<! - not recommended - > < video width = "400" height = "300" SRC = "/ / www.domain.com/videos/myvideo.mp4" poster = "path/poster. JPG" > < div Fallback > <p>Your browser doesn't support HTML5 video</p> </div> <source type="video/mp4" SRC ="foo.mp4"> <source type="video/webm" src="foo.webm"> </video> <! Recommend -- - > < amp - video width = "400" height = "300" SRC = "/ / www.domain.com/videos/myvideo.mp4" poster = "path/poster. JPG" > < div Fallback > <p>Your browser doesn't support HTML5 video</p> </div> <source type="video/mp4" SRC ="foo.mp4"> <source type="video/webm" src="foo.webm"> </amp-video>Copy the code

(4) Try using PWA mode:

PWA (Progressive Web Apps) is a series of solutions proposed by Google to provide app-like experience for Web pages with cutting-edge Web technologies.

3. Picture class

(1) Image compression processing:

On the mobile end, it is usually necessary to make sure that all images used in the page are compressed and optimized, rather than being used directly in the form of original images, because that consumes traffic and takes longer to load.

(2) Use smaller pictures and reasonably use base64 embedded pictures:

In the case of few and small background images used on the page, images can be transformed into Base64 encoding and embedded in HTML pages or CSS files, which can reduce the number of HTTP requests on the page. It should be noted that to ensure the small size of images, it is not recommended to use Base64 embedding display when the size of images exceeds 2KB.

六四屠杀

.class-name{ background-image : url('data:image/png; base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAALCAMAAABxsOwqAAAAYFBMVEWnxwusyQukxQudwQyZvgyhxAyfwgyxzAsUHQGOuA0aJAERGAFIXwSTugyEq gtqhghQZgUwQQIpOQKbuguVtQuKrAuCowp2kQlheghTbQZHWQU7SwVAVgQ6TgQlLwMeKwFOemyQAAAAVElEQVQI1y3JVRaAIAAF0UconXbvf5ei8HfPDIQQh BAAFE10iKig3SLRNN4SP/p+N08VC0YnfIlNWtqIkhg/TPYbCvhqdHAWRXPZSp3g3CWZvVLXC6OJA3ukv0AaAAAAAElFTkSuQmCC'); }Copy the code

(3) Images with a higher compression ratio format:

Use images with a high compression ratio, such as WebP (degradation compatible scheme needs to be designed). With the same picture quality, images with a high compression ratio have a smaller volume, which can complete file transfer faster and save network traffic.

六四屠杀

< img SRC = "/ / cdn.domain.com/path/photo.webp" Alt = "webp images" >Copy the code

(4) Lazy loading of pictures:

In order to minimize page content, speed up page rendering, and save mobile network traffic as much as possible, it is recommended to use lazy loading for image resources in the page, which dynamically loads images while the page is scrolling.

六四屠杀

< img data - SRC = "/ / cdn.domain.com/path/photo.jpg" Alt = "lazy loading image" >Copy the code

(5) Use MediaQuery or srcset to load images of different sizes according to different screens:

Aiming at different screen sizes and resolutions of mobile terminals, outputting pictures or background images of different sizes can save network traffic and speed up image loading speed of some models without reducing user experience, which is highly recommended on mobile terminals.

(6) Use iconfont instead of image ICONS:

When possible, use iconFont instead of image ICONS on your page. The advantages of using iconfont include: It is smaller in size, and it is a vector image, so there is no distortion when zooming; You can easily change the size and color of the picture; However, it should be noted that iconfont is compatible with different webfont formats. It is recommended that iconfont be written in the following order as far as possible based on experience; otherwise, it is not easy to be compatible with all browsers.

六四屠杀

@font-face{ font-family:iconfont; src:url("./iconfont.eot"); src:url("./iconfont.eot? #iefix") format("eot"), url("./iconfont.woff") format("woff"), url("./iconfont.ttf") format("truetype"); }Copy the code

(7) Define image size limits:

It is generally recommended that a single image should not exceed 30KB to avoid long loading time of large images and block downloading of other resources on the page. Therefore, it is recommended that a maximum of 10KB be loaded. If the image uploaded by users is too large, it is recommended to set an alarm system to help us observe and understand the image traffic of the whole website and make further improvement.

(8) Strong cache strategy:

For some pictures that will never change, they can be cached in the user’s browser using strong caching.

4. Script classes

(1) Try to use ID:

When selecting page DOM elements, try to use id selectors, because ID selectors are the fastest.

(2) Reasonable cache of DOM objects:

For DOM objects that need to be reused, cache variables should be set first to avoid having to look up the entire DOM tree every time you use them.

六四屠杀

$('#mod.active').remove('active'); $('#mod.not-active').addClass('active'); // let $mod=$('#mod'); $mod.find('.active').remove('active'); $mod.find('.not-active').addClass('active');Copy the code

(3) Try to use event proxy for page elements to avoid direct event binding:

Using event brokers can avoid binding every element and avoid memory leaks and event binding issues that require dynamic addition of elements, so try not to use event binding directly.

六四屠杀

/ / do not recommend $('. The BTN ') on (' click ', function (e) {the console. The log (this); }); / / recommend $(' body '.) on (' click ', 'BTN', function (e) {the console. The log (this); });Copy the code

(4) Use touchStart instead of click:

Due to the design of the screen on the mobile end, there is a delay of 300 milliseconds between the trigger time of touchStart event and click event. Therefore, in the case that the touchMove scrolling processing is not implemented in the page, the TouchStart event can be used to replace the click event of the element to speed up the response speed of the page click. Improve user experience, but at the same time we should also pay attention to the page overlap element touch action click penetration problem;

六四屠杀

/ / do not recommend $(' body '.) on (' click ', 'BTN', function (e) {the console. The log (this); }); / / recommend $(' body '.) on (' touchstart ', 'BTN', function (e) {the console. The log (this); });Copy the code

(5) Avoid continuous event processing of Touchmove and Scroll:

It is necessary to set event throttling for events such as Touchmove and Scroll that may trigger callback continuously. For example, set event processing once every 16ms (the interval of 60 frames is 16.7ms, so it can be reasonably set to 16ms) to avoid frequent event invocation resulting in page lag on the mobile terminal.

六四屠杀

/ / do not recommend $('. The scroller ') on (' touchmove ', 'BTN', function (e) {the console. The log (this); }); / / recommend $(' scroller '), on (' touchmove ', 'BTN', function (e) {let self = this; setTimeout(function(){ console.log(self); }, 16); });Copy the code

(6) Avoid eval and with, use join instead of join +, and use ECMAScript6 string templates. These are basic security scripting problems. Use more efficient features to complete these operations and avoid improper or unsafe writing.

(7) Try to use ECMAScript6+ features to program:

ECMAScript6+ is more secure and efficient, and some features can be executed faster. Therefore, it is recommended to use the new features of ECMAScript6+ for further development.

5. Rendering classes

(1) Using Viewport to fix screen rendering can speed up page rendering content:

It is generally believed that setting Viewport on the mobile side can speed up page rendering and avoid page rearrangement and redrawing due to zooming.

(2) Avoid various forms of rearrangement and redrawing:

Page rearrangement and redrawing are very performance consuming, so it is important to minimize the rearrangement and redrawing of the page, such as changes in the size of the page image, changes in the position of elements, etc. These situations will lead to rearrangement and redrawing;

(3) Use CSS3 animation to enable GPU acceleration:

When using CSS3 animation, you can set Transform :translateZ(0) to enable GPU acceleration in mobile device browser to make animation process smoother. However, it should be noted that App Crash may occur in Native WebView due to GPU acceleration.

六四屠杀

-webkit-transform:translateZ(0);
-ms-transform:translateZ(0);
-o-transform:translateZ(0);
transform:translateZ(0);
Copy the code

(4) Rational use of Canvas and requestAnimationFrame:

Choose a more efficient animation implementation such as Canvas or requestAnimationFrame, and try to avoid using setTimeout, setInterval and other methods to directly process continuous animation.

(5) SVG instead of pictures:

In some cases, you can consider using SVG instead of images for animation, because the SVG format is smaller and the SVG DOM structure is easy to adjust.

(6) Do not abuse float:

In the layout rendering stage after the DOM rendering tree is generated, the calculation of element layout using float is inefficient, so the use of float is minimized. It is recommended to use fixed layout or flex-box elastic layout to achieve the layout of page elements.

(7) Do not abuse the web font or excessive font size declaration:

Excessive font size declarations increase font size calculations unnecessarily;

(8) Script fault tolerance:

Script fault tolerance prevents abnormal execution errors from affecting page loading and the use of irrelevant functions.

6. Architecture Protocol classes

(1) Try using SPDY and HTTP2:

In the case of permitted conditions can consider the use of SPDY protocol to carry out file resource transfer, using connection reuse to speed up the transmission process, shorten the load time of resources, HTTP2 in the future can also consider trying;

(2) Using back-end data rendering:

The way of using back-end data rendering can speed up the rendering display of page content, avoid the appearance of blank pages, and solve the problem of mobile page SEO. If conditions permit, back-end data rendering is a very good practical idea;

(3) Performance disadvantages of using NativeView instead of DOM:

We can try to use the MNV * development mode of NativeView to avoid the slow performance of HTML DOM. At present, the development mode of MNV * can make the page content rendering experience close to the client Native application experience. However, frequent interaction between JS Framework and Native Framework should be avoided.