Frontend Performance Optimization-mobile browser optimization policy and frontend Performance Optimization

Source: Internet
Author: User
Tags prefetch http 2

Frontend Performance Optimization-mobile browser optimization policy and frontend Performance Optimization

Summary: Front-end performance optimization is a very broad concept. The previous sections of this book also mention more or less some front-end optimization methods, which is an important thing we have been paying attention. In combination with various methods, means, and auxiliary systems, front-end optimization aims at improving user experience and page performance. We often do our best to optimize front-end pages, however, it ignores the effect and significance of this operation. First, let's not rush to explore how the front-end optimization can be done. First, let's look at what is front-end performance and how to understand and evaluate the performance of front-end pages.

Compared with desktop browsers, mobile Web browsers have some obvious features: small device screens, better compatibility with new features, support for some new HTML5 and CSS3 features, and interaction with Native applications. However, the CPU computing resources and network resources available for mobile browsers are extremely limited. Therefore, more things need to be done to optimize mobile Web.

First, in front-end page rendering of mobile Web, the optimization rules on the desktop browser are also applicable. In addition, some extreme optimizations are also required for mobile terminals to achieve better results. It should be noted that the optimization principle on the mobile end is not applicable on the desktop browser, but is more representative on the mobile end due to compatibility and differences.

I. network loading

1. Data requests on the first screen are requested in advance, so that data is not requested after JavaScript files are loaded.

To further speed up page loading, you can consider making data requests on the page as early as possible to avoid data requests after JavaScript loading is complete. Generally, data requests are the longest part of the Key Path in page content rendering, and cannot be parallel. Therefore, if you can advance data requests, You can greatly shorten the Page Content Rendering completion time.

2. First screen loading and On-Demand Loading, non-first screen content scrolling, to ensure that the content of the first screen is minimized

Because the network speed of the mobile terminal is relatively slow and network resources are limited, In order to load the page content as soon as possible, we need to ensure that the loading resources on the first screen are minimized, and the content on the non-first screen is asynchronously loaded in scrolling mode. Generally, it is recommended that the latency of data presentation on the first screen of a mobile page not exceed 3 seconds. Currently, China Unicom's 3G network speed is 338KB/s (2.71 Mb/s). Therefore, we recommend that the size of all resources on the first screen not exceed 1014KB, that is, about 1 MB.

3. Parallel download of modular Resources

In mobile resource loading, we try to ensure parallel loading of JavaScript resources. This mainly refers to asynchronous loading of modular JavaScript resources, such as AMD's asynchronous modules, parallel loading can shorten the loading time of multiple file resources.

4. CSS and JavaScript necessary for the inline first screen

Generally, to make the browser have basic styles when HTML is loaded, you need to inline the necessary CSS and JavaScript For page rendering to the page through <script> or <style>, avoid page blank when HTML loading is complete to display the page content.

<! DOCTYPE html>

<Html lang = "en">


<Meta charset = "UTF-8">

<Title> example </title>

<Meta name = "viewport" content = "width = device-width, minimum-scale = 1.0, maximum-scale = 1.0, user-scalable = no">


/* Necessary CSS for the first screen */

Html, body {

Margin: 0;

Padding: 0;

Background-color: # ccc;






5. Set dns pre-resolution for meta DNS prefetch

Configure DNS pre-resolution for file resources, so that the browser can parse the Host IP address of the static resources in advance to avoid waiting for the request to initiate DNS resolution requests. Generally, the following methods can be used in mobile HTML.

<! -- Cdn Domain Name Pre-resolution -->

<Meta http-equiv = "x-dns-prefetch-control" content = "on">

<Link rel = "dns-prefetch" href = "//">

6. Resource pre-loading

Resources that may be used after the mobile terminal's first screen is loaded must be loaded as soon as possible after the first screen is loaded to ensure that the resources have been loaded when the user needs to browse, at this time, it would be very slow to make asynchronous requests again.

7. make proper use of MTU policies

Generally, we think that the Maximum Transmission Unit (MTU) of TCP network Transmission is 1500B, that is, a network RTT (Round-Trip Time, network request Round-Trip Time) the maximum amount of data that can be transferred within the time is 1500 bytes. Therefore, in the Development Mode of front-end isolation, try to ensure that the HTML content of the page is less than 1 kb, so that the entire HTML content request can be completed within an RTT time, increase the HTML loading speed to the maximum extent.

Ii. Cache

1. Make Rational Use of browser cache

In addition to using Cache-Control, Expires, Etag, and Last-Modified to set the HTTP Cache, you can also use localStorage on the mobile terminal to save the data returned by AJAX, you can also use localStorage to save CSS or JavaScript static resource content to implement offline applications on the Mobile End, minimize network requests, and ensure fast loading of static resource content.

2. offline static Resources solution

For mobile applications or Hybrid applications, you can set an offline file or offline package mechanism to allow static resource requests to be read from the local device to speed up resource loading and implement offline updates. We will focus on this part in later chapters.

3. Try to use AMP HTML

Amp html can be used as a solution to optimize front-end page performance. The elements in AMP Component are used to directly render the original page elements.

<! -- Not recommended -->

<Video width = "400" height = "300" src = "" poster = "path/poster.jpg">

<Div fallback>

<P> Your browser doesn't support HTML5 video </p>


<Source type = "video/mp4" src = "foo.mp4">

<Source type = "video/webm" src = "foo. webm">


<! -- Recommendation -->

<Amp-video width = "400" height = "300" src = "" poster = "path/poster.jpg">

<Div fallback>

<P> Your browser doesn't support HTML5 video </p>


<Source type = "video/mp4" src = "foo.mp4">

<Source type = "video/webm" src = "foo. webm">


Iii. Image

1. Image Compression

On the Mobile End, it is usually necessary to ensure that all the images used on the page are compressed and optimized, rather than directly used in the form of the original image, because it consumes a lot of traffic and takes a longer loading time.

2. Use a smaller image to properly use base64 embedded Images

When the page uses a small number of background images, you can convert the image into base64 encoding and embed it into an HTML page or CSS file. This reduces the number of HTTP requests on the page. Note that to ensure that the image size is small, we do not recommend base64 embedded display when the image size exceeds 2 kb.

. Class-name {

Background-image: url ('data: image/png; base64, Bytes/p + N08VC0YnfIlNWtqIkhg/TPYbCvhqdHAWRXPZSp3g3CWZvVLXC6OJA3ukv0AaAAAAAElFTkSuQmCC ');


3. Use images with a higher compression ratio

Use images with a high compression ratio, such as webp. In the case of the same image quality, images with a high compression ratio are smaller, enabling faster file transmission and Saving network traffic.

4. Image lazy loading

To minimize page content, accelerate page rendering, and minimize network traffic on the Mobile End, we recommend that you use lazy loading for image resources on the page to dynamically load images during Page scrolling.

5. Use Media Query or srcset to load images of different sizes based on different screens

In the responsive section, we learned that for different mobile terminal screen sizes and resolutions, the output of images or background images of different sizes can save network traffic without reducing the user experience and speed up image loading for some models. This is highly recommended on mobile terminals.

6. Use iconfont to replace the image icon

Use iconfont instead of the image icon on the page as much as possible. The advantages of this method are as follows: the use of iconfont is small and vector, so it will not be distorted During Scaling; you can easily modify the image size and color. However, it should be noted that iconfont references the compatibility of different webfont formats. It is recommended to write in the following order 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 ");


7. Define the image size limit

It is generally recommended that the size of a single image be smaller than 30 kb to prevent the download of other resources on the page from being blocked due to the long loading time of the large image. Therefore, we recommend that you set the size to less than 10 KB. If the image uploaded by the user is too large, it is recommended to set up an alarm system to help us observe the picture traffic of the entire website and make further improvements.

Iv. scripts

1. Try to use the id Selector

Use the id selector whenever possible when selecting DOM elements on the page, because the id selector is the fastest.

2. Properly cache DOM objects

For DOM objects that need to be reused, cache variables should be set first to avoid re-searching from the entire DOM tree each time.

// Not recommended

$ ('# Mod. activity'). remove ('active ');

$ ('# Mod. not-active'). addClass ('active ');

// Recommended

Let $ mod = $ ('# mod ');

$ Mod. find ('. activity'). remove ('active ');

$ Mod. find ('. not-activity'). addClass ('active ');

3. Use event proxy whenever possible for page elements to avoid direct event binding

Using Event proxy can avoid binding each element, and avoid Memory leakage and event binding requiring dynamic addition of elements. Therefore, do not directly use event binding.

// Not recommended

$ ('. Btn'). on ('click', function (e ){

Console. log (this );


// Recommended

$ ('Body'). on ('click', '. btn', function (e ){

Console. log (this );


4. Use touchstart instead of click

Due to the design of the mobile screen, there is a 300 millisecond delay between the trigger time of the touchstart event and the click event, so when the page does not implement the touchmove rolling process, you can use the touchstart event to replace the click Event of the element to speed up the response to page clicks and improve the user experience. But at the same time, we should also pay attention to the click Penetration Problem of the page overlapping element touch action.

// Not recommended

$ ('Body'). on ('click', '. btn', function (e ){

Console. log (this );


// Recommended

$ ('Body'). on ('touchstart', '. btn', function (e ){

Console. log (this );


5. Avoid handling touchmove and scroll continuous events

You need to set event throttling for events that may trigger callback consecutively, such as touchmove and scroll. For example, you can set the interval between 60 frames to 16.7 ms, so it can be reasonably set to 16 ms) to avoid the freezing of mobile pages due to frequent event calls.

// Not recommended

$ ('. Scroller'). on ('touchmove', '. btn', function (e ){

Console. log (this );


// Recommended

$ ('. Scroller'). on ('touchmove', '. btn', function (e ){

Let self = this;

SetTimeout (function (){

Console. log (self );

}, 16 );


6. Avoid using eval and with, and use join instead of connector +. We recommend using the string template of ECMAScript 6.

These are some basic security scripting issues. Try to use more efficient features to complete these operations to avoid nonstandard or insecure writing.

7. Use the features of ECMAScript 6 + as much as possible for programming

To some extent, ECMAScript 6 + is more secure and efficient, and some features are executed faster, which is also required by future specifications. Therefore, we recommend that you use the new features of ECMAScript 6 + to complete subsequent development.

5. Rendering

1. Fixed Screen Rendering using Viewport to accelerate page rendering content

It is generally believed that setting Viewport on the mobile end can accelerate page rendering and avoid page re-painting due to page re-arrangement due to scaling. Set the fixed Viewport on the mobile end as follows.

<! -- Set viewport not to zoom -->

<Meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no">

2. Avoid Reprinting in various forms

Page re-painting is very performance-consuming, so we must minimize page re-painting, such as page image size changes, element location changes, and so on, will lead to re-painting.

3. Use CSS3 animation to enable GPU Acceleration

With CSS3, you can set transform: translateZ (0) to enable GPU image processing acceleration for mobile device browsers, making the animation process smoother.

-Webkit-transform: translateZ (0 );

-Ms-transform: translateZ (0 );

-O-transform: translateZ (0 );

Transform: translateZ (0 );

4. Reasonable Use of Canvas and requestAnimationFrame

Select Canvas, requestAnimationFrame, and other more efficient animation implementation methods to avoid using setTimeout, setInterval, and other methods to directly process continuous animation.

5. Use SVG to replace Images

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

6. Do not abuse float

In the layout rendering phase after the DOM rendering tree is generated, the use of float element layout computing is relatively performance-consuming, so we should minimize the use of float, we recommend that you use a fixed layout or flexible flex-box layout to implement the layout of page elements.

7. Do not abuse web fonts or too many font-size statements

Too many font-size statements increase the font size and are not necessary.

Vi. Architecture protocols

1. Try to use SPDY and HTTP 2

If conditions permit, you can use the SPDY protocol to transfer file resources. connection multiplexing can accelerate the transmission process and shorten the resource loading time. HTTP 2 can also be considered in the future.

2. Use backend Data Rendering

The backend Data Rendering Method can accelerate the rendering and display of page content to avoid the appearance of blank pages and solve the SEO problem on mobile pages. If conditions permit, backend Data Rendering is a good practice. The following sections describe the relevant content of backend Data Rendering.

3. Performance disadvantage of replacing DOM with Native View

You can try Native View's MNV development mode to avoid slow html dom performance. Currently, the MNV development mode can bring the Page Content Rendering experience closer to the client's Native application experience.

The common technical methods and ideas for page optimization mainly include the above. Although many of them are listed, there may still be a few omissions. It can be seen that front-end performance optimization is not a simple task, it involves a lot of content. You can apply these methods to your project based on your actual situation. It is almost impossible to implement them all, but it is easy to implement the principle that is acceptable to users.

At the same time, we must be clear that we have made great efforts to optimize the system, but also paid a lot of money. This is also a problem of front-end optimization. In theory, these optimizations can be achieved, but as engineers, we must also understand the trade-offs. Optimization improves the user experience and makes data loading faster, but the project code may be disrupted. asynchronous content needs to be split out. A sprite image on the first screen may be divided into two parts, the Code maintenance cost of the page project doubles, and the project structure may become chaotic.

Therefore, asynchronous automatic processing should be well solved during the design and construction of components solutions in the early stage. Any part of optimization can be done in depth, but not necessarily worth it. We should also try our best to consider cost-effectiveness while optimizing, this is the correct thinking we should have when dealing with front-end optimization as a front-end engineer.

Series of articles:

Frontend performance optimization (I) frontend performance analysis:

  • Https://

Frontend performance optimization (2) desktop browser frontend optimization policy:

  • Https://

Frontend performance optimization (3) browser frontend optimization policy for mobile terminals:

  • Https://

This article is excerpted from the book "Modern front-end technology analysis".

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.