Front-end performance Optimization (ii): Mobile browser front-end optimization strategy

Source: Internet
Author: User
Tags prefetch browser cache http 2

Relative to the desktop browser, there are some obvious features on the mobile web browser: Small device screen, good compatibility with new features, support for some newer HTML5 and CSS3 features, need to interact with native applications, etc. But mobile browsers have a very limited amount of CPU computing and network resources available, so it's often necessary to do more to optimize the mobile web. First, in the front-end page rendering of the mobile web, the optimization rules on the desktop browser are equally applicable, and some extreme optimizations are made for the mobile side to achieve better results. It is important to note that not the optimization principle of the mobile side is not applicable on the desktop browser side, but because of compatibility and differences, some optimization principles are more representative on the mobile side.

First, the Network load class

1. First screen data request in advance, to avoid the JavaScript file loading before requesting data

To further increase the page loading speed, consider taking the page's data request as early as possible to avoid requesting data after the JavaScript is loaded. Typically, data requests are the longest part of a critical path in page content rendering, and cannot be parallel, so if you can advance the data request, you can greatly shorten the rendering finish time of the page content.

2. First screen loading and loading on demand, not the first screen content scrolling load, to ensure the first screen content minimized

Because the mobile network speed is relatively slow, network resources are limited, so in order to complete the loading of page content as soon as possible, need to ensure that the first screen loading resources minimized, non-first screen content using scrolling asynchronous loading. Generally recommended mobile page first screen data display delay maximum of 3 seconds. At present, China Unicom 3G network speed of 338kb/s (2.71mb/s), so the recommendation of the first screen all the resource size of not more than 1014KB, that is, about not more than 1MB.

3. Parallel download of modular resources

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

4. Inline first screen essential CSS and JavaScript

Usually in order to make the HTML load complete when the browser has a basic style, you need to render the page when the necessary CSS and JavaScript through <script> or inline <style> to the page, to avoid page HTML loading completed to the page content of the process of the page appears blank.

<! DOCTYPE html>

5. Meta DNS prefetch setting DNS pre-parsing

Set the DNS pre-resolution of the file resource so that the browser resolves the host IP that gets the static resource in advance and avoids waiting for the request to initiate a DNS resolution request. This can usually be done in the mobile HTML as follows.

<!--CDN Domain pre-resolution--><meta http-equiv= "X-dns-prefetch-control" content= "on" ><link rel= "dns-prefetch" href = "//cdn.domain.com" >

6. Resource Pre-loading

For the mobile end of the first screen may be used after the resources, need to load the first screen as soon as possible after loading, to ensure that the user needs to browse the load has been completed, this time if the asynchronous request will appear very slow.

7. Reasonable use of MTU strategy

Typically, we think that the maximum transmission unit (Maximum transmission UNIT,MTU) for a TCP network transmission is 1500B, which is the network one RTT (round-trip time, Network request round-trip time) the maximum amount of data that can be transferred is 1500 bytes. Therefore, in the front-end separation of the development model, as far as possible to ensure that the HTML content of the page within 1KB, so that the entire HTML content request can be completed within a RTT time request, to maximize the speed of HTML loading.

Second, the Cache class

1. Make reasonable use of browser cache

In addition to using Cache-control, Expires, ETag, and last-modified to set the HTTP cache, you can use Localstorage on the mobile side to save the data returned by Ajax. Or use Localstorage to save the content of CSS or JavaScript static resources, realize the off-line application of mobile, minimize the network request and ensure the fast loading of static resource content.

2. Offline solution for static resources

For mobile or hybrid applications, you can set up offline files or offline package mechanisms to allow static resource requests to be read locally, speed up resource onboarding, and enable offline updates. We will focus on this piece of content in a later chapter.

3. Try using amp HTML

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

<!--not recommended--><video width= "height=" "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><!--recommended- <amp-video width= "height=" 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>

Third, the picture class

1. Image compression Processing

On the mobile side, it is generally important to ensure that all images used in the page are compressed and optimized, rather than being used directly in the original image, because that consumes traffic and takes longer to load.

2. Use a smaller image, use base64 inline images properly

In the case where the background image used by the page is small and low, the image can be converted into an base64 encoding embedded in an HTML page or CSS file, which reduces the number of HTTP requests for the page. Note that to ensure that the picture is small, the general picture size of more than 2KB is not recommended to use Base64 embedded display.

. class-name {Background-image:url (' data:image/png;base64, Ivborw0kggoaaaansuheugaaaaoaaaalcamaaabxsowqaaaayfbmvewnxwusyqukxqudwqyzvgyhxayfwgyxzasuhqgoua0ajaergafixwstugyeqgtqhghqz Guwqqipoqkbuguvtqukraucowp2kqlheghtbqzhwqu7swvavgq6tgqllwmekwfoemyqaaaaveleqvqi1y3jvraaiaaf0uconxbvf5ei8hfpdiqqhbaafe10ik IG3SLRNN4SP/P+N08VC0YNFILNWTQIKHG/TPYBCVHQDHAWRXPZSP3G3CWZVVLXC6OJA3UKV0AAAAAAAELFTKSUQMCC ');}

3. Use higher-compression Beagle pictures

Use a picture with a higher compression beagle, such as WEBP. In the case of the same picture quality, high-compression beagle-style pictures are smaller, can complete file transfer faster, save network traffic.

4. Picture Lazy Loading

In order to minimize the content of the page, speed up the rendering of the page, as far as possible to save mobile network traffic, the picture resources on the page is recommended to use lazy loading implementation, when the page scrolling dynamic loading pictures.

5. Use media query or Srcset to load different sizes of pictures based on different screens

In the introduction of the response of the section we learned that for different mobile screen size and resolution, the output of different size of the picture or background map to ensure that the user experience is not reduced under the premise of saving network traffic, speed up some models of the picture loading speed, which is highly recommended on the mobile side.

6. Use Iconfont instead of picture icons

The advantages of using Iconfont instead of picture icons in the page are as follows: Using Iconfont is small and vector, so you can easily modify the size and rendering color of your pictures. However, it is important to note that Iconfont refers to the compatibility of different webfont formats, according to the experience recommended as far as possible to write in the following order, 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 picture size Limits

Loading a single picture is generally recommended not more than 30KB, to avoid large picture loading time and blocked the download of other resources, so recommended within 10KB. If the user uploads the picture too large, it is recommended to set up an alarm system, help us to observe the entire site to understand the picture traffic situation, to make further improvements.

Iv. Script Classes

1. Use the ID selector as much as possible

Use the ID selector whenever possible when selecting a page DOM element because the ID selector is the fastest.

2. Caching Dom Objects reasonably

For DOM objects that need to be reused, set the cache variables first, and avoid re-locating the entire DOM tree each time it is used.

$ (' #mod. Active ') is not recommended. Remove (' active '); $ (' #mod. not-active '). addclass (' active ');//Recommended Let $mod = $ (' #mod '); $mod. Find ('. Active '). Remove (' active '); $mod. Find ('. not-active '). addclass (' active ');

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

Using event proxies avoids binding on each element and avoids memory leaks and event-binding issues that require adding elements dynamically, so try not to use event bindings directly.

$ ('. Btn ') is not recommended. 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 delay of 300 milliseconds between the Touchstart event and the Click event Trigger time, so the Touchstart event can be used instead of the click event of the element in cases where touchmove scrolling is not implemented in the page. Speed up the responsiveness of page clicks and improve user experience. But at the same time we should also pay attention to the page overlap element touch Action Click-through problem.

$ (' body ') is not recommended. On (' click ', '. Btn ', function (e) {Console.log (This)}); /recommended $ (' body '). On (' Touchstart ', '. Btn ', function (e) {console.log (this);});

5. Avoid touchmove, scroll continuous event processing

Event throttling needs to be set for events such as Touchmove, scroll, which can trigger callbacks in a row, such as setting every 16ms (frame interval of 60 frames to 16.7ms, so it can be set reasonably to 16ms) before an event is processed, avoiding frequent event calls causing the mobile page to stutter.

$ ('. Scroller ') is not recommended. On (' Touchmove ', '. Btn ', function (e) {console.log (this);}); /Recommended $ ('. Scroller '). On (' Touchmove ', '. Btn ', function (e) {Let's = this; SetTimeout (function () {console.log (self);}, 16) ;});

6. Avoid using eval, with, use join instead of Connector +, recommend using ECMAScript 6 string template

These are some of the basic security scripting issues that you can do with a more efficient feature to avoid irregular or unsafe writing practices.

7. Try to program with ECMAScript 6+ features

ECMAScript 6+ is somewhat more secure and efficient, and some feature execution is faster and is a requirement for future specifications, so it is recommended to use the new features of ECMAScript 6+ to complete the later development.

V. Rendering class

1. Fixed screen rendering with viewport to accelerate page rendering content

It is generally believed that setting viewport on the mobile side can speed up rendering of the page, while avoiding scaling causes the page to redraw. The method of fixing the viewport settings on the mobile side is as follows.

<!--set viewport do not scale--><meta name= "viewport" content= "Width=device-width, initial-scale=1.0, maximum-scale= 1.0, User-scalable=no ">

2. Avoid various forms of reflow redraw

The reflow redraw of the page is very expensive, so be sure to minimize reflow redrawing of the page, such as changes in the size of the page picture, changes in the position of the element, and so on, which can result in reflow redrawing.

3. Use CSS3 animations to turn on GPU acceleration

With CSS3 animations, you can set Transform:translatez (0) to turn on GPU graphics acceleration for your mobile device browser, 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 way to implement animations such as canvas or requestanimationframe, and avoid using settimeout, setinterval, and so on to directly handle continuous animations.

5. SVG instead of picture

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

6. No misuse of float

In the layout rendering stage after the DOM render tree is built, the element layout of float is used to calculate the performance of the comparison, so the use of float is minimized, and the layout of the page elements is recommended using a fixed layout or a flex-box elastic layout.

7. Do not misuse web fonts or excessive font-size claims

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

VI. Architecture Protocol Classes

1. Try using Spdy and HTTP 2

It is possible to consider using the SPDY protocol for file resource transfer, using the connection multiplexing to speed up the transfer process and shorten the load time of the resources, if conditions permit. HTTP 2 can also be considered in the future.

2. Using back-end data rendering

The use of back-end data rendering can speed up the rendering of page content, avoid the appearance of blank pages, but also to solve the problem of mobile page SEO. Back-end data rendering is a good practice if conditions permit. Later chapters will detail the content of back-end data rendering.

3. Performance disadvantage of using native view instead of DOM

You can try using the MNV development mode of the native view to avoid slow HTML DOM performance, and the current development model using MNV has been able to bring the page content rendering experience closer to the experience of the client native app.

The common technical means and ideas about page optimization mainly include these, although the list of many, but there may still be a few omissions, visible front-end performance optimization is not a simple thing, it involves a lot of content. You can apply these methods to your project according to the actual situation, it is almost impossible to do it all, but it is easy to achieve the principle that the user can accept.

At the same time we have to be clear that we have achieved extreme optimization at the same time also paid a great price, which is also a front-end optimization problem. Theoretically, these optimizations are achievable, but as engineers we also have to understand the tradeoffs. Optimization improves the user experience, makes the data load faster, but the project code can be disrupted, asynchronous content to split out, the first screen of a sprite chart may be divided into two, page project code maintenance costs multiplied, the project structure may become chaotic. So it is necessary to solve the problem of asynchronous automatic processing when designing the building and component solution. Any part of the optimization can be done in depth, but not necessarily all worth, in the optimization as far as possible to consider cost-effective, this is what we as a front-end engineer to deal with the front-end optimization should have the correct thinking.

Front-end performance Optimization (ii): Mobile browser front-end optimization strategy

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: info-contact@alibabacloud.com 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.