Original link: http://caibaojian.com/mobile-optimization.html
Due to the environmental limitations of mobile devices, such as low bandwidth, high latency, small memory, low processor performance, etc., forcing developers to find ways to optimize the performance of front-end pages to meet user performance expectations. In highlighting how to address mobile performance issues, this article summarizes some examples of front-end optimizations and outlines some methods and strategies for accelerating pages.
Why performance can affect so much
No matter how interesting, beautiful and interactive your page design is, whether it's on the desktop or on a mobile device, if the page takes 2-3 seconds to render the display, the user will quickly become impatient. It can be expected that, when the page is still loading, the user is likely to move from browsing the purchase to clicking the fallback button or shutting down the browser's behavior.
A delay of less than 1 seconds can even significantly affect revenue. In 2006, Marissa Mayer, who was also working at Google, said that Google had experimented with 30 as users said they wanted to see more than 10 search results on a search page. But surprisingly, in this experiment, traffic and investment were reduced by 20%, apparently because more search results resulted in more than half a second to load the page. ^5
The user's expectations are always rising. In 2009, a study by Akamai, a Forrester Institute, found that the threshold for Web page response time was 2 seconds, and that 40% of users would abandon the page once the page was over 3 seconds in time. A year later, another study by Akamai showed that the percentage of users who abandoned browsing pages for more than 3 seconds rose to 57%. ^1,7
In addition, mobile users want pages on mobile devices to perform as much as desktop PCs. The Harris Interactive 2011 Mobile Interactive Survey, commissioned by Tealeaf Technology (now integrated into IBM), shows that 85% of adults who have had a mobile spending experience in the previous year want the experience on a mobile device to be comparable to, or even better than, a laptop or PC. And 63% said that once he had a problem with trading on mobile devices, they would no longer want to buy other products from the company through other channels. ^10 in other words, poor mobile page performance can affect the sales of various other platforms in the company, including, of course, offline physical stores.
Mobile traffic is growing rapidly. For many consumers, their mobile phones or tablet devices have become the main gateway to their web browsing, but their performance is not satisfactory. In February 2011, a study commissioned by Compuware, a equation research institute, found that almost half of mobile users (46%) said their websites were loading too slowly. 60% of the users want the page to load in 3 seconds or less, and 74% of the users say that when a single page load takes 5 seconds or more, they choose to leave the page. In 2012, a study of 200 leading e-commerce Web sites, launched by the Strangeloop network (now integrated into Redware), showed that in 3G network environments, The average load time is 11.8 seconds (Figure 1), while in the LTE (4G) environment, the load time is only slightly improved for 8.5 seconds. ^8
Three influencing factors for performance of mobile devices
As mentioned above, mobile devices inherently have the following three performance limitations: Low bandwidth, small memory, and low processor performance. These performance challenges are compounded by some other problems, such as:
The page is larger than before. based on the analysis of the HTTP Archive Web site, an average Web page now needs to load more than 1MB of data, including images, Javascript,CSS (cascading Style Sheets), and more. A larger web page can affect the display performance of your desktop PC. For mobile performance-especially in 3G environments-the impact is more severe. The impact will be more pronounced in the next three years. By 2015, the average page size will reach 2MB, with the current page growth rate.
There is a huge difference in latency. for LTE, the latency is about 34ms, and for 3G, latency is about 350 milliseconds or more. The latency of the mobile is the only constant is the delay time is always uncertain, even in the same place, each time the delay is uncertain. This is because a large amount of data is transmitted through the information tower. So the direction of the weather, even the bearer, is likely to be a factor of influence.
download speed varies greatly. the download speed ranges from 1Mbps in 3G to 31Mbps in LTE environments. Comparing this to the average bandwidth of 15Mbps in the United States is a very interesting thing, 3G environment than the average bandwidth is 15 times times slower, and LTE can reach the average bandwidth of twice times that fast.
M.sites does not completely solve the problem of mobile performance.
Many web site developers try to develop short, fast, streamlined m.sites for multi-user access, large Web pages, and low-traffic-connected access pages; However, these attempts are of little use and when users have the option, up to 35% of mobile users will choose to browse the full site.
Those who choose to browse the full site are obviously more likely to buy than users who browse m.sites. A study shows that the mobile end of each $7.00 consumption, there is $5.50 from the site of the site browsing, only $1.00 is from M.sites, the remaining $0.50 is from the client. ^9
Solve the problem
The main strategy for improving website performance is not changing from a PC to a mobile phone or tablet device, but with some small strategies.
In both PC and mobile browsers, only 20% of the time it takes to display the page is used to read the HTML of the page. The remaining 80% is used to load additional resources such as stylesheets, script files, or pictures, and to execute the client program.
The three main strategies for improving performance are:
- Reduce the number of HTTP requests per page that need to get additional resources
- Reduce the size of each request load
- Optimize client execution priorities and script execution efficiency
Because mobile networks are usually slower than the network of desktop machines, it is important to reduce the number of requests and the amount of load requested. Optimizing the client program is also critical because the browser of the mobile side parses the HTML and executes JavaScript less efficiently than the desktop PC. In addition, the cache size of the mobile browser is lower than the desktop PC, so there is a need to have a way to reuse the local cache resources.
The remainder of the article summarizes the ways to solve these problems. While most of these methods can be automated, they can also be solved manually by experienced front-end engineers. The key is to know how to manually solve these techniques to control resource requests. Often in CMS (Content management System) or other Web applications, some pages contain automatically generated or offline HTML fragments, CSS or JavaScript files, so that the page developers do not need to optimize them.
Reduce requests
The biggest performance flaw is that a page needs to launch dozens of network requests to get resources such as stylesheets, scripts, or pictures. This has a more severe impact on relatively low bandwidth and high latency mobile device connections. CDNs (content distribution network) puts resources closer to the user's location to solve this problem, but the impact of a large number of requests on page load time is more serious than the request. And recent discoveries have shown that CDNs's performance impact on mobile users is getting lower.
The following sections discuss several ways to simplify HTTP requests.
Consolidate resources
For developers, putting JavaScript code and CSS styles in a common file for multiple page sharing is a standard optimization method. This method can be very simple to maintain the code, and improve the efficiency of client cache usage.
In a JavaScript file, make sure that the same script in one page is not loaded more than once. This redundant script is easy to come up with when large teams or multiple teams are working together. You may be very surprised at how often it happens not to be low.
Sprites is a technique for working with pictures in CSS. Sprites is the integration of multiple images into a linear mesh of large images. The page can be used to retrieve this large image once and as a CSS background, and then use the CSS background positioning properties to show the image part of the page. This technique consolidates multiple requests into one, which can significantly improve performance.
Implementation tips: Smooth improvement but requires control over resources. Depending on the developer's Web site permissions, some resources do not need to be integrated (for example, some resources generated by the CMS). Also, for resources referenced by some external domains, forced consolidation can cause problems. It is important to note that the integration of resources is a double-edged sword for mobile browsers. Consolidating resources does reduce requests on first-time access, but large resource files can lead to cache invalidation, so you need to carefully consolidate resources using a variety of technologies to optimize your local storage.
Use browser cache and local cache
All browsers now use local resources to cache resources that are tagged with cache-control or expires headers that mark the time the resource needs to be cached. In addition, the ETAG (Entity label) and last-modified headers identify whether a request needs to be re-requested after the resource expires. In order to reduce unnecessary server requests, the browser gets the resources from the local cache as much as possible and cleans up those resources that have been out of date, or when the cache space is reduced. Browser caches usually include images, Css,javascript code, which can reasonably improve the performance of the site. (for example, to support back and forward buttons, use a separate cache to hold the entire rendered page).
Mobile browser caching is usually much smaller than a desktop PC, which causes the cached data to be cleaned up very often. HTML5 's cache provides a good alternative to browser-based caching. JavaScript's localstorage has been implemented on all major desktop and mobile browsers. Using script code can easily support HTML5 localstorage operation, can read and write key value data, each domain name is about 5MB capacity. Although the speed of reading and writing varies widely across mobile browsers, Localstorage's large cache makes it well suited as a client cache. Getting resources from Localstorage is significantly faster than getting resources from the server, and is more flexible and reliable on most mobile devices than relying on the cache header or the local cache of the browser. This is a place where mobile browsers are more advantageous than desktop PCs, where local caches still prioritize the use of standard browser caches, causing desktop PC local cache performance behind the mobile browser.
Implementation tips: further consideration is required. Although the mechanism of localstorage is easy to implement, some of its control mechanisms are very complex. You need to consider all the issues that the cache brings to you, such as cache invalidation (when do I need to delete the cache?). ), the cache is missing (what does it do when you want the data to be in the cache?). And what do you do when the cache is full?
Embed resources in HTML when first used
The standard for HTML is to use links to load external resources. This makes it easier to update these resources on the server (or on a Cdn), rather than modifying them on each page. As discussed above, this pattern also allows the browser to fetch resources from the local cache rather than the server.
But for resources that have not yet been cached to the browser localstorage, this model has a negative impact on the performance of the site. In general, a page requires dozens of separate requests to fetch resources to render the page. So, from a performance standpoint, if a resource doesn't have a high probability of being cached, it's best to embed it in the HTML of the page (called inlining) instead of using the link outside. Scripts and styles are supported inline with HTML, but images and other binary resources can also be embedded in HTML by embedding Base64 encoded text.
The downside of embedding is that the size of the page can become very large, so for Web applications it is critical to be able to track and analyze when the resource needs to be fetched from the server and when it has been cached to the client. In addition, you must be able to use code to cache resources on the client after the first request, so using HTML5 localstorage on a mobile device is a good way to embed.
Implementation tips: smooth processing. Because you do not know whether the user has visited this page, it is necessary to have a mechanism for the site to generate different versions of the page.
Sending events using the HTML5 server
Web applications have used various methods of polling resources from the server to continuously update pages. HTML5 's EventSource objects and Server-sent events can open a one-way channel for a server-side connection client through the browser-side JavaScript code. The server can use this write channel to send data, which saves the consumption of HTTP to create multiple polling requests. This approach is more efficient than HTML websocket. The websocket scenario is that when there are many client and server interactions (such as messages or games), a two-way channel is established on the full-duplex connection.
Implementation tips: further consideration is required. This technology is based on specific technologies. If your site is currently polled using other Ajax or comet technologies, turning it into a server-sent event requires refactoring the Web site's JavaScript code.
Eliminate redirects
When a user accesses a desktop PC website on a mobile device, the Web site application usually reads the HTTP user-agent header to determine if the user is from a mobile device. The app then sends an HTTP 301 (or 302) request with an empty HTTP body and a redirect HTTP address header, redirecting the user to the mobile version of the Web site. However, this additional client and server interaction typically consumes hundreds of milliseconds on the mobile network. Therefore, passing a mobile Web page on the original request would be faster than passing a redirected message and having the client request the move page again.
For those who want to see a desktop PC site on a mobile device, you can provide a link to the mobile Web page, which can also indicate that your site does not advocate this behavior.
Implementation tips: Although this technique is theoretically simple, it is not actually easy to implement. Because some m.sites are hosted elsewhere, many sites choose to redirect to a different server. Some websites will grow cookies when redirecting requests to tell the Web app that the user is using a mobile device. This approach may be more manageable for Web applications.
Reduce resource load
Size issues. Render smaller pages faster and get smaller resources faster. Reducing the size of each request is often not as significant as reducing the number of page requests to improve performance significantly. However, there are some technologies that can be of great benefit in terms of performance, especially in mobile environments where bandwidth and processor performance are needed.
Compress text and images
Compression techniques such as gzip rely on the steps of increasing server-side compression and browser decompression to reduce the load on resources. However, in general, these operations are highly optimized. And the test shows that the compression on the site still plays an important role in optimizing performance. Those text-based responses, including Html,xml,JSON (JavaScript Object Notation), JavaScript, and CSS, can reduce the size by about 70%.
The browser affirms its decompression technique in the accept-encoding request header, and when they receive the content-encoding response header that is returned by the server, it automatically extracts it according to the response header.
Implementation tips: easy to implement. If set correctly, all Web servers now support compression responses. However, there are also some desktop PC security tools that remove the accept-encoding header from the request header so that the user cannot get a compressed response even if the browser supports decompression.
Code simplification
Simplification is often used in scripts and style files to remove unnecessary characters, such as spaces, line breaks, or annotations. Names that do not need to be exposed to an external name can be shortened to one or two characters, such as variable names. The right simplification of resources usually does not require any additional processing on the client, and reduces the resource size by an average of 20%. Scripts and style files that are embedded in HTML can also be streamlined. There are a lot of good libraries for streamlined operations, and these libraries generally provide services that combine multiple files to reduce the number of requests.
The benefits of simplification are not limited to bandwidth and latency, but are also improved for large resources that cannot be saved on mobile devices. Gzip does not help in this respect, because resources are cached after being decompressed.
Implementation tips: easy to implement. Google's closure compiler has incredibly accomplished the work of understanding and simplifying JavaScript. But the simplification of CSS is not so easy, because there are different CSS techniques for different browsers to confuse the CSS simplification tool, and then make the CSS is not working properly after simplification. It is important to note that there is already such a case, even if you just delete unnecessary characters, simplifying the work may also destroy the page. So, once you've applied the simplification technique, do a complete functional test.
Resizing a picture
Images are often used to load most Web pages and occupy the main space of page caching. The small-screen mobile device provides the opportunity to speed up the transfer and rendering of picture resources by resizing the picture. High-resolution images can waste bandwidth, processing time, and cache space if the user simply looks at a picture in a small mobile browser window.
To speed up page rendering and reduce bandwidth and memory consumption, you can resize the picture dynamically or replace the picture with a smaller version that is specific to your mobile device. Do not rely on the browser to convert high-resolution images into small-size images, which can waste bandwidth.
Another way to do this is to load a low-resolution image as soon as possible to render the page, replacing these low-resolution images with a high-resolution image after onload or the user has started interacting with the page.
Implementation tips: special applications in highly dynamic sites are advantageous.
Simplify pages with HTML5 and CSS 3.0来
HTML5 includes a number of new structural elements, such as header,nav,article and footer. Using these semantic elements makes the page simpler and easier to parse than the traditional use of div and span tags. A simple page with smaller loads is faster, and the simple Dom (Document Object Model) represents a faster JavaScript execution efficiency. New tags can be quickly applied to new browser versions that include the mobile side, and the HTML5 design allows browsers that don't support it to smoothly transition to new tags.
Some of the form elements of HTML5 provide a number of new properties to complete functionality that would otherwise require JavaScript. For example, the new placeholder property is used to display introductory text that appears before the user enters the input box, and the Autofocus property is used to indicate which input box should be automatically positioned.
There are also some new input box elements that can accomplish some common requirements without relying on JavaScript. These new input box types include elements such as E-mail,url, numbers, ranges, dates and times that require complex user interaction and input validation. On a mobile browser, when you need to enter text, the keyboard that pops up is usually chosen by a particular type of input box. Browsers that do not support the specified input type will display only one text box.
In addition, as long as the browser supports built-in hierarchies, fillets, shadows, animations, transitions, and other picture effects, CSS 3.0 can help you create easy-to-use pages, which were originally needed to load images to complete. In this way, these new features will speed up page rendering.
There are many Web sites that provide updates on which mobile or desktop browsers support which performance update description. (Example: http://caniuse.com/and mobilehtml5.org).
Implementation tips: further consideration is required. It is very complex and time-consuming to make these changes manually. If you use CMS, it can help you generate many HTML and CSS that you don't need to control.
Optimizing Program handling for clients
In what order the browser executes the code to generate a page, and the page complexity and the technical choice of JavaScript, all have a great impact on performance. This is especially noticeable on the client's relatively slow CPUs and less-memory mobile. The following sections provide some strategies to improve the performance of page processing.
Deferred rendering of "below-the-fold" content
What is certain is that if we delay loading the contents of the invisible area, the page will be displayed more quickly in front of the user, and this area is called "below the fold". To reduce the content that needs to be re-accessed after the page is loaded, you can replace the picture with the correct tag labeled by the aspect.
Implementation tips: smooth processing. Some good JavaScript libraries can be used to handle these below-the-fold lazy loading images. ^12
Deferred read and Execute scripts
On some mobile devices, parsing JavaScript code can take up to 100 milliseconds per gigabyte. Many of the script's libraries are not required to be loaded until the page is rendered. Downloading and parsing these scripts can be safely deferred to the OnLoad event. For example, some behaviors that require user interaction, such as hold-and-drag, are unlikely to be called until the user sees the page. The same logic can also be applied to script execution. Try to defer execution of the script to the OnLoad event, rather than when it is important to be seen by the user on the initialization page.
These delayed scripts may have been written by you yourself, and more importantly, it could be a third party. Poor scripting optimizations for ads, social media parts, or analytics can cause blocked page rendering, adding valuable load times. Of course, you need to carefully evaluate a large scripting framework such as jquery, designed for mobile web sites, especially when you're just using some of those objects in the framework.
Implementation tips: smooth processing. Many third-party frameworks now provide an asynchronous version of the API for lazy loading. Developers simply need to translate the original logic into this asynchronous version. Some javascript is a bit more complicated to delay loading because it takes a lot of attention to execute these scripts after onload. (For example, if you have a script that needs to be bound to the OnLoad event, what do you need to do?) If you defer the script to the OnLoad event, you will lose a lot of execution time. )
Using AJAX to enhance processes
Ajax (asynchronous JavaScript and XML) is a technology that uses XHR (XMLHttpRequest) objects to get data from a Web server, and it does not need to update a running page. Ajax can update a portion of a page without having to rebuild the entire page. It is usually used to submit the user's interaction, but it can also be used to load the frame portion of the page first, and then fill in the details when the user is ready to browse the page.
Although this is the name, XMLHttpRequest does not mandate that you use XML only. You can use JSON to replace XML by calling the Overrideminetype method to make a "Application/json" type. Using Json.parse is almost twice times faster and more secure than using the native eval () function.
At the same time, remember that the return response of Ajax will also benefit from the application of the normal return response optimization techniques. Make sure that your AJAX return response uses a cache header, simplified, gzip compression, and resource merging techniques.
Implementation tips: Because this technology is different depending on the application, it is difficult to quantify. Perhaps because of cross-domain issues, you need to use XHR2, a technique that can use resources from external domains to make cross-domain XHR requests.
Adaptive processing based on network conditions
Because more bandwidth is used to charge more mobile networks, only the types that can detect the network can use optimized technologies for specific networks. For example, it is very clever to preload a request for future use, but this technique is unreasonable if the user's bandwidth is scarce and some of the resources loaded are never used.
The return value of the Android 2.2+,navigator.connection.type property allows you to differentiate between WiFi and 2g/3g/4g networks. On the BlackBerry, Blackberry.network can also provide similar information. In addition, the server detects the network condition by detecting the user-agent header in the request or other information embedded in the request to allow your application to be detected.
Implementation tips: further consideration is required. The API for detecting network information has recently changed. The ^11 interface now does not directly define network conditions such as wi-fi,3g, but rather gives bandwidth information and recommendations such as "very slow, slow, fast and very fast". There is a property that gives an estimated MB/s value and a Boolean value of "Meterd" to indicate its credibility, but it is difficult for a browser to judge the environment by this. Judging the current network environment and then adapting is still the best approach, but this approach is being considered for replacement.
Use the HTML5 Web Worker feature for multithreading as much as possible
The web worker in HTML5 is executing JavaScript programs concurrently with multiple threads. In addition, this special multithreaded implementation can reduce the confusion of developers for many years, on other platforms encountered problems. For example, when a thread needs to change what to do with a resource that is being used by another thread. In a web worker, a child thread cannot modify the resources used by the main user interface (UI) thread.
For improving the performance of mobile sites, the code in the Web worker is well suited to preprocess the resources the user needs to complete further operations, especially if the user's bandwidth resources are not scarce. On mobile devices with low processor performance, excessive preload can interfere with the UI response of the current page. Using multithreaded code, let the Web Worker object (and use Localstorage to cache the data as much as possible) manipulate the preloaded resources in another thread, so that the current UI performance is not affected.
In particular, WEB worker is only available on Android version 2.0, and the previous version of iOS5 on the iphone is not supported. On the desktop PC, always lag behind IE only in IE 10 support Web Worker.
Implementation tips: smooth transitions. While this technique is not very difficult to implement, there are some restrictions that need to be enforced for web workers. The WEB workers cannot go into the DOM of the page, nor can it change anything on the page. Web worker is well suited for work that requires background computing and processing.
Replace the Click event with the Touch event
On a touchscreen device, when a user touches the screen, the OnClick event is not immediately triggered. The device uses about half a second (most devices are almost 300 milliseconds) to let the user determine whether it is a gesture action or a click action. This delay can significantly affect the user's expected response performance. To be resolved, use the Touchend event to replace. This event is immediately triggered when the user touches the screen.
You should also use the Touchstart and Touchmove events in order to ensure that the user does not expect the behavior to occur. For example, unless there is also a Touchstart event on the button, do not judge that the Touchend event on the button means the click Behavior-because the user is likely to touch the start from somewhere else, and then drag to the end of the button touch. You can also use the Touchmove event after the Touchstart event to avoid mistaking the Touchend event for clicks, assuming that the drag gesture is not intended to produce click behavior.
Also, you need to handle the OnClick event to let the browser change the appearance of the button to identify the clicked State, and you need to deal with browsers that do not support touch events. To avoid code repetition in the Touchend and onclick code, you need to invoke the Preventdefault and Stoppropagation methods in the Click event after you have ensured that the user touches the event already executed in Touchend. ^4
Implementation tips: further consideration is required. This technology requires more work to add and maintain links in a single page. The code for the touch event must consider other gestures, since replacing the click may also be a scaling or tapping action.
Support Spdy Protocol
Some of the performance bottlenecks caused by the application-layer HTTP and HTTPS protocols make it uncomfortable for both desktop and mobile sites. In 2009, Google began to develop a protocol called Spdy ("speedy") to replace existing agreements, which claim to be able to break these limits. The goal of this protocol is to allow multiple browsers and multiple Web services to be supported, so this protocol is open source, but initially only Google's Chrome browser (in version 10 and later) and Google's site support. Once a Web service supports SPDY, all of its sites can interact with Spdy that support this protocol. By applying Spdy to 25 top100 Internet sites, Google collects data that will improve the speed of the site by 27% to 60%. ^2
Spdy automatically uses gzip to compress all content, and unlike HTTP, it even uses gzip compression for header data. Spdy uses multithreading techniques to allow multiple request flows or response streams to share a single TCP connection. In addition, Spdy allows the request to set priority, for example, the video in the center of the page will have a higher priority than the border ad.
Perhaps the most transformative invention in spdy is that the flow is bidirectional and can be initiated by the client or the server, which enables the information to be pushed to the client without the client initiating the first request. For example, when a user browses a site for the first time and there is no cache for the site, the server can push all the requested resources in the response, instead of waiting for each resource to be requested separately. As a replacement protocol, the server can send hints to the client to indicate what resources are required for the page and also allow the client to initialize the request. Even using the latter method is faster than having the client parse the page and then find out what resources it needs to be requested.
Although Spdy does not have any special settings for mobile, the limited bandwidth on the mobile side makes it useful for spdy to reduce the latency of mobile sites if Spdy is supported.
Source: Front-end Development blog
Mobile Site Performance Optimization: page load (GO)