1. An overview of the

Generally speaking, front-end performance optimization refers to the process from the beginning of users’ visit to our website to the complete display of the whole page, through various optimization strategies and optimization methods to make the page load faster, so that users’ operation response is more timely, and give users a better use experience.

Here we introduce the front-end performance optimization knowledge of the solution, starting from static resource optimization, from the representation of the in-depth systematic explanation of the page rendering architecture, master the funny technical scheme.

This article is not a detailed description of how to achieve performance optimization, but a comprehensive overview of how to achieve performance optimization, and not just H5, because today’s front-end is not just H5.

2. Image resource optimization

1. Picture format introduction

Jpeg: A lossy compressed graphic format widely used for color photographs. Is a raster graphics, commonly used file extensions JPG, JPEG, JPE. It is often used to store and transfer photos on the Internet. Not suitable for line graphics and text, icon graphics, because his compression algorithm does not support these types of graphics, and does not support transparency. It is often used for colorful photos, color images, large focus images, banners and other irregular graphics.

PNG: portable network graphics, is a lossless compression bitmap graphics format, support index, gray, RGB three colors, and Alpha channel features. It was originally designed as a replacement for GIF, with support for translucent and transparent features, up to 24-bit color graphics and 8-bit grayscale images. However, the file size is too large because of lossless compression. Good for solid colors, transparency, line drawings, ICONS, and images with less color that require translucency.

GIF: bitmap graphics file format, 8-bit color reproduction of true-color images, encoded using LZW compression algorithm. Support 256 colors, only fully transparent and completely opaque, can support GIF, but only 8 bits per pixel, not suitable for storing color pictures. Often used with animations and ICONS.

Webp: is a modern image format that provides both lossless and lossy compression. Can simultaneously certify a certain program on the image quality and small volume, you can insert multiple frames, to achieve animation effects. Support transparency. Using an 8-bit compression algorithm, lossless WebP is 26% smaller than PNG, lossy WebP is 25-34% smaller than JPEG and has better animations than GIF. However, it can handle up to 256 colors, not suitable for color pictures. Often used for graphics and translucent images.

2. Image optimization

For PNG images, jDF-pnG-native can be used for compression. It is a package of Node-PngQuant-Native tools. This tool is cross-platform, has a high compression ratio, and compresses PNG24 very well.

const pngquant = require('jdf-png-native');
const fs = require('fs');

fs.readFile('./in.png'.(err, buffer) = > {
    if (err) {
        throw err;
    }
    const resBuffer = pngquant.option({}).compress(buffer);
    fs.writeFile('./out.png', resBuffer), {
        flags:'wb'
    }, () = >{})})Copy the code

JPG compression can be done using the jpegtran tool, which is also a Node tool. It is simple to use the command directly. It’s about a 10% reduction.

jpegtran -copy node -optimize-outfile out.jpg in.jpg
Copy the code

For GIF files, you can use the gifsicle tool, which reduces the GIF file size by changing the scale of each frame, and can use transparency to achieve a smaller file size. Is a recognized solution. You can go to http://www.lcdf.org/gifsicle/ to install. The command line mode is also used.

gifsicle --optimize=3 --crop-transparency -o out.gif in.gif
Copy the code

The optimization level here should not be less than 2, where 1 means no compression. After compression, the frame does not break.

Another way to compress images is to display images of different sizes and pixels according to the network environment, by adding different parameters to the URL suffix. For example, in the following address,430 can be changed to 800 to obtain images of different sizes.

https://img.alicdn.com/imgextra/i1/2616970884/O1CN01x6HnoK1IOuj5IosXO_!! 2616970884.jpg_430x430q90.jpg

3. Responsive images

The responsive image means that we can display pictures of different sizes under the condition of different window sizes and device pixels of users. It can be realized in the following three ways. The first way is to use JS to bind events to detect the window size, so as to set the size of the picture. The second method is CSS media query.

@media screen and (max-width:640) {
    my_image { width:640px; }}Copy the code

The third can be set using HTML5’s SRcSet, which automatically selects the image you want based on the pixel ratio of the device. Browsers that do not support srcset will display SRC properties as normal.

<img srcset="img-320w.jpg, img-640w.jpg 2x, img-960w.jpg 3x" src="img-960w.jpg" alt="img" />
Copy the code

4. Step by step method of loading images

This is lazy loading, where a public image, usually the company logo, is used before the real image is loaded, and the layout is propped up and then replaced with the real image.

Lqip is a tool that can transform real images into tiny Base64 encoding. So we can use Base64 to load the blurred image first.

npm install lqip
Copy the code
const lqip = require('lqip');
const file = './in.png';
// image
lqip,base64(file).then(res= > {
    console.log(res); / / output base64
})
// color
lqip.paletter(file).then(res= > {
    console.log(res); // Image color value
})
Copy the code

You can also use low-quality image placeholders, which are based on SVG image placeholders.

npm install sqip
Copy the code
const sqip = require('sqip');

const result = sqip({
    filename:'./in.png'.numberOfPrimitives:10 / / value effect
});

console.log(result.final_svg); // Output SVG format
Copy the code

Sqip works much better than LQIP and can be set to different sizes.

5. Other ways

You can use Web Fonts instead of images, such as small business images such as ICONS.

You can also use dataURL (base64) instead of images so that the user doesn’t need to send an HTTP request.

Sprite can also be used to combine multiple small images into one large image, which will also save a lot of image requests.

6. Picture server automatic optimization

Picture server optimization means that different special parameters can be added to the picture URL connection, so that the server automatically generates pictures of different formats, sizes and qualities.

For example, you can do some cutting of the picture, cut into the picture we need, can also support the conversion of different formats, such as JPG, GIF, PNG, webP, etc., can also set the image compression ratio.

You can also add some watermarks, Gaussian blur, center of gravity processing to the picture and increase some AI capabilities, such as whether the picture uploaded by the user is pornographic. You can also improve pictures through intelligent matting, intelligent typesetting, intelligent color matching and intelligent synthesis.

3. Optimization method of HTML

1. Simplify HTML code

You can reduce the nesting of HTML, which is to say, the hierarchy, or you can reduce the DOM node count, which is to say, minimize the number of DOM nodes that the browser renders.

Reduce non-semantic code such as

if possible and preferably not.

It is recommended to delete HTTP or HTTPS from the connection, because the protocol header of a link is the same as the protocol header of the page, and it is meaningless to add 4-5 characters to them. And you can reduce the size of your code.

You can also remove unnecessary whitespace, newlines, indentation, and unnecessary comments. Compression tools typically handle this process. You can omit some tags and attributes. Use relative path urls to minimize the number of bytes.

2. File location

CSS file links should be placed at the head of the page. CSS loading will not block DOM Tree parsing, but will block DOM Tree rendering and subsequent JS execution. This means that the DOM Tree parses the CSS before rendering to reduce the number of times the browser rearranges the document. CSS at the bottom of the page causes the page to go white for a longer time.

Js files are usually placed at the bottom of the page, which prevents JS loading and parsing from blocking the normal rendering of page elements.

3. User experience

Setting up favicon.ico will cause an error if the console is not set, and the address bar is empty when the user accesses it, which is bad for brand memory.

Add necessary CSS and JS to the first screen. Generally, the page will not be displayed until all dependencies are loaded, which will lead to blank pages. Yongxiang user experience, you can add background images or loading or skeleton screen, much better than blank page.

4. CSS optimization rules

1. Improve the CSS rendering performance

Use expensive attributes, such as the NTH-Child dummy class or position: Fixed, with caution, because they cost the browser a lot of rendering performance.

Try to reduce the number of style levels, for example, div ul Li SPAN I {color:red}, in fact, we can set the I tag to class, directly write style.

Avoid using attributes that take up too much CPU and memory, such as text-indent.

Avoid using high-power properties, such as transfrom is, transitions, and opacity, instead of occupying the GPU.

Use CSS selectors appropriately. Avoid wildcards and CSS expressions. color:expression((new Date()).getHours() % 2 ? “# FFF” : “# 000”).

Avoid property selectors for class regulars. * = | = ^ =, $=, use of CSS, outside the chain can be individually documented in CDN, use the cache form to load. Avoid using @import because its loading blocks the process and does not proceed until it is loaded.

Simplify CSS code by using abbreviated statements, such as margin-top can be written in margin, and can be deleted if the value is 0. Remove unnecessary unit values, excessive semicolons, Spaces and comments. Minimize the size of the stylesheet. In fact, these can be used to deal with compression tools, will be a lot more convenient.

2. Use Web Fonts properly

Font files can be deployed on the CDN to accelerate the loading speed of the client. Fonts can also be stored in the CSS as Base64 and cached through localStorage. Some Google font libraries should use a domestic hosting service rather than directly using the source address.

3. CSS animation optimization

Avoid animation at the same time, that is to say, there should not be too much animation in the screen area visited by users. Too much animation will interfere with the normal browsing of the website, and animation will also affect the performance of the browser.

Delay the initialization of the animation, allowing other CSS to render first, and delay the animation by, say, 0.5 or 1.

Animations can be displayed using SVG, and styles can be controlled in CSS.

5. JavaScript optimization

First of all, we optimize when we need to, not for optimization’s sake. Generally, optimization is carried out at a certain point in time, and optimization also needs to consider maintainability, which is based on the team’s research and development level and code specifications.

1. Improve the loading performance of JS files

Everyone knows that CSS files go in the head tag and JS files go at the end of the body. This is js loading and does not affect HTML rendering.

2. Optimization of variables and functions

Try to use ID selectors because ID selectors are the most efficient in terms of query results.

Avoid eval, which consumes rows.

Keep js functions as simple as possible and don’t put too much into one function. Throttling functions for events are also recommended. Event delegate and so on.

3. Js animation

Try to avoid adding a lot of JS animation, CSS3 animation and Canvas animation are better than JS animation performance.

Use requestAnimationFrame instead of setTimeout and setInterval, because requestAnimationFrame can render at the correct time, setTimout and setInterval cannot guarantee rendering timing. Do not bind events to timers.

4. Use logical caching

Caching dom objects, that is, storing them in a variable, rather than querying them every time you use them.

Cache list length, that is, the number of DOM elements stored in a variable rather than recalculated each time.

For example, Baidu M station, will put the page CSS and JS in the local storage, so that after the loading time directly from the local storage, to achieve the effect of the second test. However, local storage space is limited, so use it with caution.

6. Reduce page backflow and redraw

1. css

Avoid excessive style nesting, and better to locate elements quickly.

Avoid using CSS expressions, which are executed throughout the CSS drawing process, increasing the number of rearrangements and reflows.

You can use absolute positioning to take animation elements out of the document flow.

Avoid table layouts, which can cause multiple browser redraws, and do not use float layouts.

It is best to set the width and height of the image so that the layout is determined after the image is loaded.

Simplify unnecessary browser tasks by using viewPort to set the screen zoom level.

Avoid frequent styling changes and merge multiple style changes in one go.

2. js

In order to reduce the number of backflow occurrences, frequent DOM manipulation should be avoided. DOM modifications can be combined multiple times and processed in batches at once.

Control the drawing process and the drawing area. Property Settings that are expensive during the drawing process should be avoided.

7. Simplify DOM operations

It is well known that a large part of the reason for the staid and fluency of the page interaction is the large number of DOM elements on the page. If you think about it, using querySelectorAll or getElementByTagName to find a node from a DOM tree with tens of thousands of nodes is time-consuming, and when the element is bound to an event, The execution of event bubbling and event capture can also be relatively time consuming. Therefore, we should be reasonably unfamiliar with the business logic and delay the DOM content to be rendered when there are too many DOM nodes.

DOM operations should be handled uniformly before being inserted into the DOM Tree. You can use fragments to set up the DOM and styles and put them together on the page.

Popular frameworks such as Angular, React, and Vue all use virtual DOM technology to simplify and reduce DOM manipulation through diff algorithms.

Static file compression tool

Html-minifier: compression HTML clean-CSS: compression tool of CSS uglip-js: compression tool of JS files

9. Browser rendering process

First the browser parses the HTML to generate a DOM Tree, then the CSS to generate a CSSOM Tree. Then JS will use DOM Api and CSSOM Api to manipulate THE DOM Tree and CSS Rule Tree to synthesize the DOM Tree and CSSOM Tree into a Render Tree.

Backflow is performed based on the generated render tree to calculate geometric information for each node, including position, size, style, and so on. The absolute pixels on each node are then obtained based on the geometry information obtained from the rendered tree and reflow.

Finally, the pixels are sent to the image processor (GPU) for page display.

Front-end page rendering can be divided into server-side rendering and client-side rendering. Server-side rendering has traditional synchronous back-end rendering, which is isomorphic to PHP, Java,.NET or the familiar Node.

Client rendering is ALSO JS rendering, front and back end separation, single page application. React, Vue,ios, Android, Hybird App, Flutter, etc.

Lazy loading, preloading, prerendering

Lazy loading, also known as lazy loading, refers to the lazy loading of certain elements in long web pages, which can be images, JS and CSS. Lazy loading has the advantage of reducing the loading of invalid resources on the current screen.

The SRC attribute of the IMG tag is set to an empty string, and the real image address is placed in data-lazy. When the page scrolls to the corresponding position, the SRC value is replaced by the data-lazy value through DOM manipulation.

Preloading means that the browser preloads certain resources, again images, JS or CSS, that will be used in the future.

In simple terms, the required resources are loaded locally in the browser and can be retrieved from the browser cache when needed, without having to start loading again. The benefit is to reduce the amount of time users have to wait to load resources later.

You can do new Image or you can do tag preload, prefetch, preconnect

<link rel="preload" href="src/style.css" />
<link rel="prefetc" href="src/image.png" />
<link rel="dns-prefetch" href="https://zhiqianduan.com" /> <! DNS cache in advance -->
<link rel="preconnect" href="https://zhiqianduan.com" /> <! Load the required resources in advance -->
Copy the code

Another way to preload a component is to render it ahead of time, rendering the component in the page but not showing it on the page, that is, hide it after rendering and show it when you use it. The https://zhiqianduan.com page can be pre-rendered using prerender.

<link rel="prerender" href="https://zhiqianduan.com" />
Copy the code

11. Optimization of interface service invocation

  1. Interface merging refers to the unified invocation of multiple service interfaces and dependent third-party interfaces on a page using the same interface deployed in a cluster to reduce the number of interface requests on the page.

  2. The CDN on the interface is mainly based on the interface performance. We can synchronize the interface that does not need to be updated in real time to the CDN, and the change of the interface content automatically synchronizes the CDN.

  3. CDN on interface domain name can enhance availability and stability.

  4. Interface degradation, this is based on the promotion of preparation consideration, the core is degraded with the basic interface for business implementation, such as thousands of recommended interface, in the promotion of time points can directly operate the edited data, in case of interface cannot access, use the preset bottom backup data.

  5. Interface monitoring, monitoring the success rate of the interface is not often said server TP99, but with the actual situation of the user has been successful and failure monitoring, such as weak network, timeout, network exceptions, network switching and other situations. Troubleshooting problems need to be solved together with back-end, operation and maintenance and network personnel.

12. Interface cache optimization

  1. Ajax/FETCH cache, the front-end request with the cache, rely on the browser’s own mechanism to request the interface, this is more suitable for data that does not change often.

  2. Local cache: Asynchronous interface data preferentially uses the data cached in the local localStorage. You can ask the server to give another MD5 value when returning data, and then save the MD5 value and data binding locally. Compare the MD5 value when requesting again. If they are the same, do not request the interface for obtaining data.

13. webview

There are two kinds of native WebView for IOS, one is UIWebView, which is easy to display Web content in App from IOS2, and has strong ability of layout.

However, UIWebView also has a lot of problems, such as memory leakage, high memory peak during operation, Touch Delay 300 milliseconds. Js does not perform well and is not maintained after ios12 in 2018.

WKWebView is a new generation of WebView component launched by Apple in WWDC 2014. WKWebView has a much smaller memory overhead than UIWebView, and has a great improvement in performance, stability and memory occupancy. It can achieve a scrolling refresh rate of 60fps, it has support for the right swipe back gesture itself, and it supports more HTML attributes. The memory usage is 1/4 ~ 1/3 of UIWebView, and the loading speed is about twice that of UIWebView. Greatly improve js execution speed. Js Nitro library is allowed, UIWebView is not allowed. Can intertune functions with JS directly, without the assistance of JsBridge.

Of course, WKWebView does not support page caching and requires its own cookie injection, whereas UIWebView automatically injects cookies. He also cannot send the POST parameter.

There are WebKit for WebView and Chromium for WebView for Android.

Webkit is an open source project, formerly known as KHTML and KJS, which focuses on the presentation of web content and makes a first-class page rendering engine. It is not a browser and does not want to be a browser. This project consists of two parts. The second part is webKit in a narrow sense, mainly porting each platform and providing the corresponding interface. Webviews and webView-like interfaces provide the ability to manipulate and display web pages.

The major browsers or WebViews that use WK include Chrome, Safari, Android, and many mobile browsers.

Chromium is a browser project based on WebKit, initiated by Google, which develops rapidly and has good support for new features, such as WebGL, CSS3, H5, etc. Chromium is also very good in performance direction, and generally chooses stable Chromium as the foundation of Chrome.

Webkit for Webview Chromium from Webview note
version Under Android4.4 Android4.4 above
JS interpreter WebCore JavaScript V8
H5 278 434
Remote debugging Does not support support Android4.4 and above support
Memory footprint small big A difference of 20-30 m
WebAudio Does not support support Android 5.0 and above support
WebGL Does not support support Android 5.0 and above support
WebRTC Does not support support Android 5.0 and above support

Android third-party kernel, mainly android version more, the WebView secondary packaging produced, here mainly say X5 kernel.

Its speed is relatively fast compared with the system WebView webpage opening speed of 30% improvement, in terms of flow using cloud optimization technology to save more than 20%. Security issues can be fixed within 24 hours. More stable after the use of hundreds of millions of users, the CRASHE(crash) rate is less than 0.15%. No fragmentation of the system kernel, smaller compatibility issues, support for night mode, suitable screen layout, font Settings and other browser enhancements. H5 and ES6 have more complete support, integrated with a powerful video player, support video format far more than the system WebView, video and file format support X5 kernel more than the system kernel, with anti-hijacking.

General webView selection, IOS recommended to use WKWebView, Android recommended to use X5.

14. WebView performance optimization

When the App is opened for the first time, the browser kernel is not initialized by default. When the WebView instance is created, the browser kernel will be launched. The event will take 70-700 milliseconds to open, and the basic framework of the WebView will be created.

The millisecond delay can be optimized by using a global Webview, which initializes a global Webview standby when the client starts up and uses the Webview directly to load the corresponding web page when the user accesses the Webview.

This reduces the time it takes to open the WebView for the first time, with the disadvantage of some extra memory consumption.

The navigation bar can be preloaded, which used to be initialized after the WebView is loaded, and can be loaded in parallel with the WebView.

For login, every time the interface on the H5 page queries whether there is a login state in the Cookie, H5 redirects to the unified login page, and the Cookie is written into the App login successfully. You can change it to Cookie and set cookies in the Webview. That is, when initializing the Webview, determine whether to log in. If you have logged in, the H5 page will be opened. If you have not logged in, the login page will be automatically redirected.

Webview loads the URL of the page as far as possible before, not at the end, can be processed in parallel with the business logic, in a word, reduce the white screen time of the page, let the user see the page as soon as possible.

To improve the experience of using the scroll bar, the original is to use the progress value of the system’s own scroll bar, which can simulate the loading process of the scroll bar itself, so that users feel that the page is loaded faster. That is, the initial fast loading to more than 60%, give the user a feeling of fast loading. The actual speed hasn’t changed…

Js-sdk optimization, which is a way for OC and JS to communicate. JSSDK generally has three ways to implement, the first is the common scheme way, that is, we define some special links in the H5 page, get the scheme after native interception. It then intercepts the required callback functions and arguments, but there is a problem with this. Urls are usually 256 characters long and cannot be passed indefinitely.

The second is in the form of IFrame, which intercepts the change of IFrame by launching a page in the background and uses js method to communicate with OC. Iframe relies on jSSDK. js file, and SDK file is needed as a bridge to achieve communication purpose.

The third method is webKit, which is a direct call method without relying on any SDK files.

Browser Cache policy

Caching mechanisms advantage Applicable scenario Android switch IOS switch
Browser caching mechanism HTTP protocol layer support Cache of static files The browser takes care of The browser takes care of
Web Storage Large storage space, easy to use Temporary, simple data cache, LocalStorage on the browser, SessionStorage webSettings.setDomStorageEnabled(true) This function is enabled by default
Web SQL Database Store and manage complex structured data IndexDB is recommended instead webSettings.setDatabaseEnabled(true) This function is enabled by default
Application Cache Easy to build offline apps Offline App, static file cache webSettings.setAppCacheEnabled(true) This function is enabled by default
IndexDB Store any type of data, easy to use, support index Structured, relational data storage webSettings.setJavaScriptEnabled(true) This function is enabled by default

15. The implementation of OFFLINE H5

A global offline package containing common resources that can be used by multiple applications.

You can also have private offline packages that can only be used by an application alone.

How the offline package works:

First loads a global package is some basic file, load after will put the package release in memory, and then do a test, to see if the local installation, if you have installed the release into memory, if not installed will trigger the offline package download, is a bag on our server, and then from the server to come over, Before downloading, a comparison will be made between the local version and the online version. If the version is inconsistent, the latest package will be downloaded. If the version is consistent, the local version will be ok.

Finally, the package will be decompressed and released in the memory. When the WebView loads the URL, it will read it directly from the memory. If it can read it, it will load the page data in the memory for display. Because we generally do not make all the business in the form of offline, assuming that the WebView query to use offline, query can not use the bottom of the online URL display. Whether the local offline package fails to load or there is no offline package, the online URL is used to the bottom.

Download of offline package If the user is in the mobile network state, the offline package will not be downloaded in the background. If the current user clicks the APP and the offline package is not downloaded, the user has to wait for the offline package to be downloaded before using it. Wifi silent download can be adopted.

When the offline package information requested by the server is stored in the local database, the offline package information includes the download address, version number, and encrypted signature information of the offline package. To install an offline package, you need to copy the offline package from the download directory to the mobile phone installation directory.

Some offline package schemes of major manufacturers, such as Meituan’s LsLoader offline scheme for universal mobile terminal WebApp, Tencent’s Alloykit offline package and Ali’s Extreme Hybrid Offline package for re-acceleration. The principle is basically consistent, some reference can be made on details.

16. Introduction to mixed development

1.RN

React Native is based on the React syntax and is intended to be a set of code that can be used on all sides. Its advantage is obvious, the code can be shared whether IOS or Android or H5, performance is almost the same as Native. It also provides very smooth animation because the code is converted to the native view before rendering.

There is no need to compile and package every code change when debugging, and the smaller effect can be viewed immediately, which greatly improves the development manpower.

Support hot update, do not need to release every release to the store, release time can be free control, Android and ios at the same time.

The implementation is divided into four layers. At the bottom is the native layer (OC and Java), above which is UI renderer, image processing, network communication, and some tool libraries. At the top is C++:JSCore, Bridge, which is the running environment of js and the Bridge between js and native. At the top is the JS layer which is the component of JS.

RN’s JSX files are packaged for different platforms using JSBridge, such as.m files for IOS,.xml files for Android, and.html files for H5.

The reason why THERE is RN is actually because of the issue of the app store version, which needs to be reviewed every time and may not pass the review. In addition, Android may have to release multiple stores, and the r&d on both ends is not synchronized, which means that the same business of Android and ios needs to be developed twice.

RN is recommended if your company’s technology is React family bucket.

2. Small programs

The vision of applets is that they are accessible, so users can open apps with a swipe or a search, without having to install too many apps.

Compared with App, the development threshold of the program is lower, which is better than the near-native experience of H5. It can use rich Native capabilities such as camera, location, network and storage. Support top pull down, search, scan code and other entrance, simple and convenient, run out of use, do not need to download like App, directly open support hot update.

The industry background of the emergence of small programs, for the large App manufacturers need to realize flow, such as wechat, he cannot realize, so he can use the ecology of small programs to introduce a third party, forming a small application market. For enterprise applications, mobile traffic dries up and it is difficult to acquire customers, which can reduce the cost of acquiring customers and development costs and provide more opportunities for trial and error in business.

If platform products are exported to merchants, it is recommended to use small programs compared with multiple apps.

3. Flutter

It claims to be written once and can be deployed to any terminal, Web, Android, ios, MAC, Linux, Windows, Fuchsia OS.

The bottom layer uses Skia graphics engine, with graphics performance comparable to native applications, and the interface is more like a full-screen application or 2D game, with relatively fast speed. The native ARM binary file is used to compile in advance, without the need for JVM, that is, Java VIRTUAL machine.

The underlying implementation

Flutter appeared in May 2017. It is not rich in ecology and has a relatively high learning curve, but it has good performance. If the performance is considered and the team is sufficient, fluTTR is recommended.

17. CDN

CDN is a content distribution network that delivers files to users faster and more reliably, using each server closest to them. To speed up access.

CDN is obvious, because users will be assigned close and smooth server nodes, so the speed will be relatively fast. The servers are placed in different locations, which reduces the traffic of interconnection and reduces the cost of fast band. When a server fails, the server in the neighboring area will be automatically called.

When a browser accesses a static file on the CDN and the file cache expires, the browser accesses the source server directly through the CDN. This is a strategy of THE CDN.

CDN cache is divided into three levels: browser local cache, that is, the cache configured in header header, CDN edge node cache, CDN source site cache. Generally, it is level 3, or two-level cache, browser cache and CDN source site cache, may be used when there is little business.

If the cache time is set too short, the CDN edge node cache often fails, leading to frequent source back, increasing the load of the source station, and slowing down the access speed. If the cache time is set too long, the file update is slow, and the user’s local cache cannot be updated in time. Therefore, it is generally determined according to the business situation.

Generally, different resource types do not set the cache time. HTML usually takes about 3 minutes, JS, CSS can take 10 minutes, a day, a month, depending on the change.

At present, the file name is usually in the form of hash string. If the file name is changed, the generated file name will be changed, otherwise it will be the same as the previous name, so that we can set the cache time longer.

CDN can be released in gray scale, that is, some operators in some regions release static resources first, and then release them in full after verification. Specific implementation can start from the domain name, set special VIP resolution to the gray level of the city or operator. You can also adjust the source station machine, for gray city or operator to configure a separate source station machine.

Generally, during activities such as promotion, it is necessary to increase machine room broadband, increase operator traffic, increase CDN cache time and so on.

18. DNS

DNS is a distributed database that maps the domain name and address of a website. When we visit a website, the domain name will be matched to an IP address through DNS, and then the IP address will be used to access the corresponding server.

The client has an HTTP DNS. The client can directly access the HTTP interface to obtain the optimal IP address configured in the domain name access system for services. For the sake of DISASTER recovery, the CARRIER’S DNS resolution mode should be reserved in the APP.

For example, in an HTTP request, the host field will be specified in the header, and it is ok to send a standard HTTP request to IP. Generally speaking, using HTTP-DNS to resolve domain names can bypass some problems that occur when third-tier and fourth-tier operators connect domain names. After the correct IP is returned by HTTP-DNS, HTTP requests are directly sent using IP. You only need to pay attention to the security of communication content.

Android can use the okHTTP module, which supports HTTP2. Http2 can send multiple requests on a link at once, supports GZIP, and supports response caching to avoid network duplicate requests. If the server is configured with multiple IP addresses, when the first IP address fails, okHTTP will automatically try the next IP address.

There is no ready-made module in ios. We can cache all the domain names and IP addresses that may be used, such as interface and gateway, when the app starts, and process them asynchronously. The client does not need to get cached results. If the domain name exists in the cache, the domain name is returned. If the domain name does not exist in the cache, the HTTPDNS server requests the domain name again.

H5 is generally set up multiple domain name, because the browser is limited to concurrency, a domain general maximum number of connections is 6, so we can will visit some of the API user interface as a domain name, the page style and resources can be set to a domain name, images can also be set to a domain name alone, and even multiple domain name, To break the browser’s limitations.

19. HTTP optimization

HTTP optimization is basically about reducing the number of requests, which is probably something we see in our daily work, and it’s also something we know a lot about.

Images can be Sprite, dataURL, webFONT.

Consider combining JS or CSS in your business. Don’t cut too small. If you don’t want to combine them into one, you can use Combo to send the service back. You can tell the service which resources to load in the FORM of parameters in the URL.

Interfaces can also be merged, do not split too fine, you can let the service to merge, do not change frequently interface and resources can also be stored in LocalSrorage, there are changes to update, no change from the local fetch.

Sometimes there is a problem with a page or a blank screen, but there is no problem with the interface or the page, and the resources can be accessed. At this time, cookies may be too large and beyond the original range of control. As we all know, cookies are carried with the jump between pages. This can cause the page to become inaccessible, which is not a common problem, but it does happen in practice.

Cookie whitelist can be set in the page, meaning that we regularly check our cookies, if it is needed to keep, do not need to delete, regular sorting. Cookie control can reduce the size of transfer between pages and can effectively manage cookies.

20. Configure the server cache

When a file is loaded by the browser we don’t actually know if the file is out of date, so there is a convention between the browser and the server to determine whether the file is out of date by configuring the header.

The response header usually contains an expires header. The value is date + time, indicating that the response expires after that time. If the value is 0, indicating that the resource has expired.

Of course, if the response header contains cache-control and the max-age or s-max-age directive is set, cache-control is ignored.

Cache-control implements the caching mechanism by specifying instructions. Cache instructions are one-way, meaning that instructions set in the request are not necessarily included in the response. Cache-control :max-age= second Sets the maximum period during which the Cache is stored, after which the Cache is considered expired.

ETag is an identifier for the version of the resource, which makes caching funnier and saves bandwidth because the Web server does not need to send a complete response if the content does not change, and if it does, using ETag helps prevent simultaneous updates of the resource from overwriting each other.

Etags are similar to fingerprints and may also be used by some servers for tracing. Comparing eTAGS can quickly determine whether a resource has changed, but they can also be persisted by the tracing server permanently.

ETag:"5c6cccc123-1d45"
Copy the code

Last-modified is a response rejection in which the resource contains the date and time of the modification to the resource identified by the source server. It is often used as a validator to determine whether received or stored resources are consistent. Since it is less precise than ETag, this is an alternate mechanism for conditional requests with if-modified-since or if-unmodified-since headers.

Date is the general header, which contains the Date and time when the packet is created.

Gzip can compress text, generally HTML, CSS, JS, but will not compress non-text, such as image resources, the compression ratio can reach 50%-70%

21. Enable HTTPS in a local test

It’s not supposed to be here, but I don’t know where.

HTTPS will not be introduced here, after all, it is not the content of this article.

Browsers already have HTTPS enabled by default, so we recommend using HTTPS for SEO purposes, and it’s much more secure.

If it is an external website, we need to purchase SSL certificates from dealers. We can purchase SSL certificates from gogetSSL, SSLs.com and SSLmate.com. Of course, these certificates are valid.

If you want to test locally, you can also install a test certificate locally, we can use mkcert to do this. First you need to install it.

brew install mkcert
Copy the code

Installing a Root Certificate

mkcert ---install
Copy the code

Generate local signatures to 123.com

mkcert 123.com
Copy the code

This creates a pair of certificates that can be configured in Nginx as described in my previous nginx article.

22. http2

Http2 is the second version of HTTP, abbreviated as H2 or H2C. It uses binary data transfer, multiplexing, and allows multiple requests to be made through a single link. Therefore, it is not useful to use H2 Sprite graph. Support server push, which can push data from the server to the client.

Enabling HTTP2 can reduce server stress, speed up site access, and better protect site security because it is mandatory to use HTTPS.

To enable http2, we need to recompile nginx and enable http_SSL_module and http_v2_module

cd nginx-xxx
./configure --with-http_ssl_module --with-http_v2_module
make && make install
Copy the code

Also refer to the nginx article I wrote earlier, which is to add the HTTP2 flag after listen port 443.

server {
    listen 443 ssl http2;
}
Copy the code

23. Front-end R&D process

Is, first and foremost, technology selection, including page rendering technology and development of hybrid technology, and then the initialization of the project, including the React, Vue, presents, rely on the module introduction, generally there is a private NPM, then began to local development, convenient front debugging and see the effect, the project alignment, the product and the designer to confirm effect, Finally, the overall deployment of the project went online.

Before the project starts, the front and back ends will specify some data interfaces. With the interface documents, the front and back ends can develop in parallel, the front end develops pages and interactions, and the back end develops business logic. After all the development, the front and back end began to carry out joint adjustment, and finally released online.

24. Automate testing

UI automation, easy to get started, but poor stability, commonly used tools include Appium, which is an open source tool for automation of ios phones, Android phones and a testing tool for Windows desktop, Robot Framework is based on Python extensible keyword testing framework for end-to-end, Acceptance testing and test-driven development can be used to test distributed heterogeneous applications, including interfaces that can be verified involving a variety of technologies. Selenium Test tools for Web applications can be run directly on the browser, and can be the same as the user’s real operation. It supports Internet Explorer, Firefox, Google, Opun and other popular browsers. It is used to test browser compatibility. Airtest supports automated script recording and one-click recycling, which is an easy way to automate the testing process and is often used.

Interface automation, stable use, very cost-effective tools, Java + RestAssured, is implemented in Java, lightweight you can write code to send requests to the client and verify the return results. Python + Requests is for python interfaces, JMeter is for stress testing, and HttpRunner requires just one script to automate performance testing, online monitoring, continuous integration, and more.

Unit testing, which is very cost-effective, is usually done by development, but there are several unit testing frameworks, Junit5, pytest, unittest.