Front-end performance optimization (3) Mobile browser front-end optimization strategy

  Compared with desktop browsers, mobile web browsers have some obvious features: smaller device screens, better compatibility with new features, support for some newer HTML5 and CSS3 features, and the need to interact with native applications. However, the CPU computing resources and network resources available to mobile browsers are extremely limited, so it is often necessary to do more things to optimize the mobile web. First of all, in the front-end page rendering of the mobile web, the optimization rules on the desktop browser also apply. In addition, some extreme optimizations are also required for the mobile terminal to achieve better results. It should be noted that it is not that the optimization principles of the mobile terminal are not applicable to the desktop browser, but that some optimization principles are more representative of the mobile terminal due to compatibility and differences.

1. Network loading class

1. The first screen data is requested in advance to avoid requesting data after the JavaScript file is loaded

  In order to further improve the page loading speed, you can consider requesting the data of the page as early as possible to avoid requesting data after the JavaScript is loaded. Usually, the data request is the longest part of the critical path in page content rendering, and it cannot be parallelized. Therefore, if the data request can be advanced, the rendering completion time of the page content can be greatly shortened.

2. Above-the-fold loading and on-demand loading, scrolling loading of non-folding content, to ensure that the content above the fold is minimized

  Because the mobile network speed is relatively slow and network resources are limited, in order to complete the loading of page content as soon as possible, it is necessary to ensure that the loading resources of the first screen are minimized, and the non-folding screen content is asynchronously loaded by scrolling. It is generally recommended that the display delay of the first screen data of the mobile page should not exceed 3 seconds. At present, China Unicom's 3G network speed is 338KB/s (2.71Mb/s), so it is recommended that the size of all resources on the first screen should not exceed 1014KB, which is about 1MB.

3. Parallel download of modular resources

  In mobile resource loading, try to ensure that JavaScript resources are loaded in parallel, which mainly refers to the asynchronous loading of modular JavaScript resources, such as AMD's asynchronous modules. Using parallel loading methods can shorten the loading time of multiple file resources.

4. CSS and JavaScript necessary for inline above the fold

  Usually, in order to make the browser have basic styles when the HTML is loaded, it is necessary to pass <script>or <style>inline the CSS and JavaScript necessary for page rendering into the page, so as to avoid the process of displaying the page content after the page HTML is loaded. The page appears blank.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>样例</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0, maximum-scale=1.0,user-scalable=no">
    <style>
    /* 必备的首屏CSS */
    html, body{
        margin: 0;
        padding: 0;
        background-color: #ccc;
    }
    </style>
</head>
<body>
</body>
</html>

5. meta dns prefetch sets DNS pre-resolution

  Set the DNS pre-resolution of file resources, let the browser resolve the host IP of static resources in advance, and avoid waiting for the request to initiate the DNS resolution request. Usually, it can be done in the following way in mobile HTML.

<!-- cdn域名预解析 -->
<meta http-equiv="x-dns-prefetch-control" content="on">
<link rel="dns-prefetch" href="//cdn.domain.com">

6. Resource preload

  For the resources that may be used after the first screen is loaded on the mobile terminal, it needs to be loaded as soon as possible after the first screen is loaded to ensure that the loading is completed when the user needs to browse.

7. Reasonable use of MTU strategy

  Under normal circumstances, we think that the maximum transmission unit (MTU) of TCP network transmission is 1500B, that is, the maximum amount of data that can be transmitted within one RTT (Round-Trip Time, network request round-trip time) of the network is 1500 bytes. . Therefore, in the development mode where the front and back ends are separated, try to ensure that the HTML content of the page is within 1KB, so that the entire HTML content request can be completed within one RTT time, which maximizes the HTML loading speed.

2. Cache class

1. Make good use of browser cache

  In addition to using Cache-Control, Expires, Etag and Last-Modified to set up HTTP cache mentioned above, you can also use localStorage on the mobile side to save the data returned by AJAX, or use localStorage to save CSS or JavaScript static resource content to achieve For offline applications on mobile terminals, network requests are minimized to ensure fast loading of static resource content.

2. Static resource offline solution

  For mobile or hybrid applications, you can set an offline file or offline package mechanism to allow static resource requests to be read locally, speed up resource loading, and implement offline updates. We will focus on this in the following chapters.

3. Try AMP HTML

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

<!-- 不推荐 -->
<video width="400" height="300" src="http://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>


<!-- 推荐 -->
<amp-video width="400" height="300" src="http://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>

3. Pictures

1. image compression

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

2. Use smaller images and use base64 inline images reasonably

  When the background images used on the page are few and small, you can convert the images into base64 encoding and embed them in HTML pages or CSS files, which can reduce the number of HTTP requests on the page. It should be noted that to ensure that the image is small, the use of base64 embedded display is not recommended for images with a size exceeding 2KB.

.class-name {
       background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAALCAMAAABxsOwqAAAAYFBMVEWnxwusyQukxQudwQyZvgyhxAyfwgyxzAsUHQGOuA0aJAERGAFIXwSTugyEqgtqhghQZgUwQQIpOQKbuguVtQuKrAuCowp2kQlheghTbQZHWQU7SwVAVgQ6TgQlLwMeKwFOemyQAAAAVElEQVQI1y3JVRaAIAAF0UconXbvf5ei8HfPDIQQhBAAFE10iKig3SLRNN4SP/p+N08VC0YnfIlNWtqIkhg/TPYbCvhqdHAWRXPZSp3g3CWZvVLXC6OJA3ukv0AaAAAAAElFTkSuQmCC');
}

3. Images using higher compression ratio formats

  Use images with higher compression ratio formats, such as webp, etc. In the case of the same picture quality, the picture volume of the high compression ratio format is smaller, which can complete the file transfer faster and save network traffic.

<img src="//cdn.domain.com/path/photo.webp" alt="webp格式图片">

4. Image lazy loading

  In order to minimize page content, speed up page rendering, and save mobile network traffic as much as possible, lazy loading is recommended for image resources on the page, and images are dynamically loaded when the page is scrolled.

<img data-src="//cdn.domain.com/path/photo.jpg" alt="懒加载图片">

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

  In the chapter introducing responsiveness, we learned that outputting pictures or background images of different sizes for different mobile screen sizes and resolutions can save network traffic without degrading the user experience and speed up the pictures of some models. Loading speed, which is highly recommended on mobile.

6. Use iconfont instead of image icons

  Use iconfont as much as possible to replace image icons in the page. The advantages of doing so are as follows: using iconfont is smaller in size and is a vector diagram, so it will not be distorted when zooming; you can easily modify the size and color of the image. However, it should be noted that iconfont refers to the compatibility of different webfont formats. According to experience, it is recommended to write in the following order, otherwise it will not 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 image size limit

  It is generally recommended that a single image to be loaded should not exceed 30KB to avoid long loading times for large images and block the download of other resources on the page. Therefore, it is recommended to be within 10KB. If the image uploaded by the user is too large, it is recommended to set up an alarm system to help us observe and understand the image traffic of the entire website and make further improvements.

4. Script class

1. try to use id selectors

  Try to use id selectors when selecting page DOM elements, because id selectors are the fastest.

2. Reasonably cache DOM objects

  For DOM objects that need to be reused, it is necessary to set cache variables first to avoid re-searching from the entire DOM tree each time they are used.

// 不推荐
$('#mod .active').remove('active');
$('#mod .not-active').addClass('active');

// 推荐
let $mod = $('#mod');
$mod.find('.active').remove('active');
$mod.find('.not-active').addClass('active');

3. Page elements should use event proxy as much as possible to avoid direct event binding

  Using event delegation can avoid binding each element, and can avoid memory leaks and event binding problems that require dynamic addition of elements, so try not to use event binding directly.

// 不推荐
$('.btn').on('click', function(e){
    console.log(this);
});

// 推荐
$('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 delay of 300 milliseconds between the touchstart event and the click event trigger time. Therefore, when the touchmove scrolling process is not implemented in the page, the touchstart event can be used instead of the element's click event to speed up page clicks. response speed and improve user experience. But at the same time, we also need to pay attention to the click penetration problem of the touch action of overlapping elements on the page.

// 不推荐
$('body').on('click', '.btn', function(e){
    console.log(this);
});

// 推荐
$('body').on('touchstart', '.btn', function(e){
    console.log(this);
});

5. Avoid touchmove, scroll continuous event processing

  It is necessary to set event throttling for events such as touchmove and scroll that may continuously trigger callbacks. For example, set event processing every 16ms (the frame interval of 60 frames is 16.7ms, so it can be reasonably set to 16ms) to avoid frequent event processing. The event call causes the mobile page to freeze.

// 不推荐
$('.scroller').on('touchmove', '.btn', function(e){
    console.log(this);
});

// 推荐
$('.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 the connector +. It is recommended to use the string template of ECMAScript 6

  These are some basic security scripting problems. Use the most efficient features to complete these operations as much as possible, and avoid irregular or unsafe writing methods.

7. Try to use ECMAScript 6+ features to program

  ECMAScript 6+ is more secure and efficient to a certain extent, and some features execute faster, which is also the need of future specifications. Therefore, it is recommended to use the new features of ECMAScript 6+ to complete subsequent development.

5. Rendering

1. Use Viewport to fix screen rendering, which can speed up page rendering content

  It is generally believed that setting the Viewport on the mobile terminal can speed up the rendering of the page, and at the same time, it can avoid the page reflow and redraw caused by zooming. The method to fix Viewport settings on the mobile side is as follows.

<!-- 设置viewport不缩放 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

2. Avoid various forms of rearrangement and repainting

  Rearrangement and redrawing of the page is very performance-intensive, so it is necessary to reduce the reflow and redraw of the page as much as possible. For example, changes in the size of page images and changes in the position of elements will lead to reflow and redraw.

3. Use CSS3 animations with GPU acceleration enabled

  When using CSS3 animation, you can set transform: translateZ(0) to enable GPU graphics processing acceleration of 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

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

5. SVG instead of images

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

6. don't abuse float

  In the layout rendering stage after the DOM rendering tree is generated, the element layout calculation using float is relatively performance-intensive, so try to reduce the use of float. It is recommended to use fixed layout or flex-box elastic layout to achieve page element layout.

7. No misuse of web fonts or excessive font-size declarations

  Excessive font-size declarations will increase the font size calculation and are not necessary.

6. Architecture protocol class

1. Try SPDY and HTTP 2

  If conditions permit, consider using the SPDY protocol for file resource transmission, and use connection multiplexing to speed up the transmission process and shorten the resource loading time. HTTP 2 can also be considered in the future.

2. Render with backend data

  Using the back-end data rendering method can speed up the rendering and 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. Subsequent chapters will introduce the content of backend data rendering in detail.

3. Performance disadvantages of using Native View instead of DOM

  You can try to use the MNV development mode of Native View to avoid the problem of slow HTML DOM performance. Currently, the MNV development mode can make the page content rendering experience close to that of the client-side Native application.

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

  At the same time, we must be clear that while we have achieved the ultimate optimization, we have also paid a great price, which is also a problem of front-end optimization. These optimizations are theoretically achievable, but as engineers, we also need to understand the tradeoffs. The optimization improves the user experience and makes data loading faster, but the project code may be disrupted. The asynchronous content needs to be split out. A sprite image on the first screen may be divided into two parts. The maintenance cost of the page project code increases exponentially, and the project structure It can also become confusing. Therefore, in the early stage, the asynchronous automatic processing problem should be solved when designing the construction and component solutions. Any part of the optimization can be done in depth, but it is not necessarily worth it. While optimizing, we should try our best to consider the cost-effectiveness. This is the correct thinking we should have when dealing with front-end optimization as a front-end engineer.

Series of articles:

Front-end performance optimization (1) Front-end performance analysis: https://my.oschina.net/zhangstephen/blog/1601380

Front-end performance optimization (2) Desktop browser front-end optimization strategy: https://my.oschina.net/zhangstephen/blog/1601382

Front-end performance optimization (3) Mobile browser front-end optimization strategy: https://my.oschina.net/zhangstephen/blog/1601383

  This article is excerpted from the book "Modern Front-End Technology Analysis" .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324537140&siteId=291194637