Tips for optimizing page load performance for mobile web sitesfavorite: 1 time: 2015-06-17 article source: Ma Haixiang Blog Visits: 2501
Web page performance optimization has been the key to the success of the site, more and more research has proved that, whether it is a small e-commerce, or large chain enterprises, even the page load time of minor improvements, can bring more business, more advertising revenue, more user stickiness and more customer satisfaction.
Over the past few years, Web developers have been optimizing the user experience based on improved hardware or bandwidth speeds, but in recent years, the use of explosive mobile Web browsers has broken this path, with low bandwidth, high latency, small memory, low processor performance, mobile device environments, Forcing developers to find ways to meet user performance expectations by optimizing the performance of front-end pages.
In what order the browser executes the code to generate a page, and the page complexity and the technical choice of JavaScript, have a great impact on performance, especially in the client's relatively slow CPUs and less memory mobile end, especially in the emphasis on how to solve the mobile performance problem, Ma Haixiang provides some strategies to improve the performance of page processing, this article summarizes some examples of front-end optimizations, and outlines some methods and strategies for accelerating pages.
1. Why does performance affect so much
No matter how interesting, beautiful and interactive your page design is, whether it's on the desktop or on the mobile device, if the page takes 3-5 seconds to render the display, the user will quickly become impatient and expect that when the page is still loading, The user is most likely to move from browsing to buying to clicking the fallback button or shutting down the browser's behavior.
Less than a 1-second delay could even have a significant impact on revenue, and in 2006, Marissa Mayer, who worked at Google, said that Google had been experimentally modified to 30 as users expressed the desire to see more than 10 search results on a search page, but surprisingly, In this experiment, traffic and investment were reduced by 20%, apparently due to more search results that took more than half a second to load the page (see the Ma Haixiang Blog "Tips on how to improve the speed of the website on the move").
The user's expectations are always rising, and in 2009, Ma Haixiang saw a study by Akamai at the Forrester Institute that showed that the threshold for Web response time was 2 seconds, and that 40% of users would abandon the page once the page was over 3 seconds, and 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%.
In addition, mobile users want pages on mobile devices to perform as much as desktop PCs, according to the "Harris Interactive 2011 Mobile Interactive Survey" commissioned by Tealeaf Technology (now incorporated into IBM): 85% of adults who have had a mobile spending experience in the previous year Expect the experience on a mobile device to be comparable to the experience on a laptop or PC, and even better, and 63% say that once he encounters a problem with a deal on a mobile device, they will no longer want to buy the company's other products through other channels, 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 today, and for many consumers, their mobile phones or tablet devices have become the main portals for their web browsing, but their performance is not as satisfactory.
In February 2011, a study commissioned by the Equation Institute, Compuware, showed that almost half of mobile users (46%) said that the website on their phone was loading too slowly, 60% of the users wanted the page to load in 3 seconds or less, and 74% said When a single page load takes 5 seconds or more, they choose to leave this 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, while in the LTE (4G) environment, the load time is only slightly improved for 8.5 seconds.
2. Three influencing factors for performance of mobile devices
In Ma Haixiang's view, mobile devices inherently have three performance limitations: Low bandwidth, low memory, and poor processor performance, plus a number of other issues, such as:
(1), the Web page is larger than before
According to the analysis of HTTP Archive Web site, now an average web page needs to load more than 1MB of data, including pictures, Javascript,css (cascading Style Sheets), and so on, the larger web page will affect the desktop PC display performance, For mobile performance, especially in the 3G environment, the impact is more serious, this impact will be more obvious in the next three years, with the current page growth rate, by 2015, the average page size will reach 2MB.
(2), the delay difference is huge
For LTE, the delay is about 34ms, for 3G, the delay is about 350 milliseconds or more, the only constant delay on the mobile side is the delay time is always uncertain, even in the same location, each time the delay is uncertain, because a large number 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.
(3), download speed difference is huge
Download speed range from 1Mbps to LTE in 3G environment 31Mbps, this and the United States average bandwidth 15Mbps is a very interesting thing, 3G environment than the average bandwidth 15 times times slower, and LTE can reach the average bandwidth of twice times that fast.
3. How to solve the problem of mobile terminal 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 of the user is obviously more than browsing m.sites users more desire to buy, a study shows that the mobile end of every $7.00 consumption, there are $5.50 from the site browsing, only $1.00 is from the m.sites, the remaining $0.50 is from the client.
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.
According to Ma Haixiang, in both PC and mobile browsers, only 20% of the time it takes for page display to read the HTML of the page, and the remaining 80% is used to load additional resources like stylesheets, script files, or images, and programs that execute the client.
The three main strategies for improving performance are:
(1), reduce the number of HTTP requests per page that need to get additional resources.
(2), reduce the size of each request load.
(3), optimize the priority of client execution and the efficiency of script execution.
Since mobile networks are usually slower than desktop machines, it is important to reduce the number of requests and load requests, and because the mobile browser is less efficient at parsing HTML and executing JavaScript than the desktop PC, optimizing the client program is also critical (see the Ma Haixiang Blog Mobile phone station front-end page SEO tips for the relevant introduction).
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 methods that can solve these problems, although most of these methods can be automated to solve, of course, can be manually solved by experienced front-end engineers, the key is to know how to manually solve the methods of these technologies how to control resource requests, usually in CMS (Content management System) or other Web applications, Some pages contain automatically generated or offline HTML snippets, CSS, or JavaScript files so that page developers don't have to optimize them.
4. Request reduction
The biggest performance flaw is that a page needs to launch dozens of network requests to get resources such as stylesheets, scripts, or pictures, which can be more severe on a relatively low-bandwidth and high-latency mobile device connection.
CDNs (content distribution network) places resources closer to the user's location to solve this problem can play a big role, but compared to the request, a large number of requests on the page load time more serious impact, and the recent discovery shows that the CDNs on the mobile user's performance impact is getting lower.
5. Integration of resources
For developers, putting JavaScript code and CSS styles in a common file for multiple page sharing is a standard optimization method that can easily maintain code and improve the efficiency of client cache usage.
In JavaScript files, to make sure that the same script is not loaded multiple times in a page, this redundant script is easy to come up with when a large team or multiple teams work together, and you may be surprised at how often it happens.
Sprites is a CSS in the processing of a picture of a technology, sprites is to integrate multiple images into a linear network of large images, the page can be used to get this big picture back and as a CSS background, and then use the CSS background positioning properties to show the page needs of the picture part, This technique consolidates multiple requests into one, which can significantly improve performance.
Smooth improvement but need to have control of the resources, according to the developer's site different permissions, some resources do not need to be integrated (for example, some of the resources generated by the CMS), and for some external domain reference resources, forced integration may cause problems, Ma Haixiang remind you to note that Integrating resources is a double-edged sword for mobile browsers, and consolidating resources does reduce requests for first-time access, but large resource files can cause cache invalidation, so you need to carefully integrate resources with a variety of technologies to optimize your local storage.
6. 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, and, in addition, The ETAG (Entity label) and last-modified header to identify if a request needs to be re-requested after the resource expires, and the browser, in order to reduce unnecessary server requests, obtain resources from the local cache as much as possible, and Or when the cache space is reduced, the long-unused resources are cleaned up, the browser cache usually includes pictures, Css,javascript code, these caches can reasonably improve the performance of the site (for example, to support the back and forward buttons, using a separate cache to save the entire rendered page).
Mobile browser cache, usually much smaller than desktop PC, which leads to the cache of data will be very often cleaned up, HTML5 cache based on the browser cache provides a good replacement scheme, JavaScript 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, the Localstorage cache makes it well suited as a client cache, and getting resources from Localstorage is significantly faster than fetching resources from the server. And on most mobile devices is more flexible and reliable than relying on the cache header or the local cache of the browser, which is a more advantageous mobile browser than desktop PC, on the desktop PC, the local cache will still prefer the standard browser cache, resulting in desktop PC local cache performance lag behind the mobile browser.
Here, Ma Haixiang to remind you: Although the localstorage mechanism is easy to implement, but some of its control mechanism is very complex, you need to consider the cache to you all the problems, such as cache failure (when need to delete 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?
7. Embed resources in HTML when first used
The standard of HTML is to use links to load external resources, which makes it easier to update these resources on the server (or on a Cdn), rather than modifying them on each page, which, as discussed above, also allows the browser to fetch resources from the local cache instead of the server.
However, for resources that have not yet been cached to the browser localstorage, this model has a negative impact on the performance of the site, and in general, a page requires dozens of separate requests for resources to render the page.
So, from a performance point of view, if a resource does not have a high probability of being cached, it is best to embed it in the HTML of the page (called inlining), rather than using the external link, scripts and styles are embedded into the HTML, However, images and other binary resources can also be embedded into 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.
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.
8. Sending events using the HTML5 server
Web applications have used a variety of methods of polling resources from the server to continuously update the page, HTML5 EventSource objects and Server-sent events can be opened through the browser-side JavaScript code a service-side connection to the client's one-way channel, The server can use this write channel to send data, which saves the consumption of HTTP to create multiple polling requests.
This is more efficient than HTML websocket, and 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 a full-duplex connection.
This technology is based on specific technologies, and if your site is currently polled using other Ajax or comet techniques, turning into a server-sent event requires refactoring the Web site's JavaScript code.
9. 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, and then the app sends an HTTP with an empty HTTP body and a redirect HTTP header 301 (or 302) request, redirect the user to the mobile version of the website, but this additional client and server interaction typically consumes hundreds of milliseconds on the mobile network, so passing a mobile Web page on the original request is faster than passing a redirected message and making the client request a 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.
Although this technique is theoretically simple, it is not actually easy to implement, Because some m.sites are hosted elsewhere, many Web sites choose to redirect to a different server, and some sites will grow cookies when redirecting requests to tell Web apps that the user is using a mobile device, which can be more manageable for Web applications.
10. Reduce Resource Load
With regard to the size of the mobile page, rendering small pages faster, getting smaller resources faster, and reducing the size of each request is often not as significant as reducing the number of page requests to improve performance significantly.
But there are technologies that can be of great benefit in terms of performance, especially in mobile environments where bandwidth and processor performance are needed.
11. Compress text and images
compression, such as Gzip, relies on the steps of increasing server-side compression and browser decompression to reduce the load on resources, but, in general, these operations are highly optimized, and the tests show that compression is also an optimized performance for the site, and 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.
Ma Haixiang that the advantage of this method is easy to implement, if set correctly, now all Web servers support compression response, but there are some desktop PC security tools will be in the request header accept-encoding, so that even if the browser support decompression, The user is also unable to obtain a response after compression.
12. Code Simplification
Simplification is usually used in scripts and style files, delete some unnecessary characters, such as spaces, line breaks, or comments, etc., do not need to expose to external naming can be shortened to one or two characters, such as variable name, the appropriate simplification of resources usually do not need to do any other processing on the client, and the average reduction of 20% The size of the resources, embedded in the HTML script and style files can also be streamlined, there are a lot of good libraries to do the streamlined operation, these libraries will also provide a combination of multiple files to reduce the number of requests for services (see the Ma Haixiang blog "Mobile site production of common methods and optimization techniques," the relevant introduction).
The benefits of simplification are not limited to reducing bandwidth and latency, and there is also a lot of improvement for oversized resources on mobile devices that cannot be saved, and Gzip does not help in this respect, because resources are cached after being decompressed.
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 let the CSS after the simplification does not work, Ma Haixiang reminds you must be aware that there is already such a case, even if just delete the unnecessary characters, simplifying the work may also break the page, so when you apply the simplification technology, please do a complete functional testing work.
13. Adjust the image size
Pictures are usually occupied by the Web page load most of the network resources, also occupy the main space of the page cache, the small screen mobile device provides the opportunity to adjust the image size to speed up the transfer and rendering of picture resources, if the user is only in a small mobile browser window to see the picture, high-resolution pictures will waste bandwidth, Processing time and cache space.
To speed up page rendering and reduce bandwidth and memory consumption, you can dynamically resize the picture or replace it with a smaller version of the mobile device, instead of relying on a browser to convert high-resolution images into small-sized pictures, which wastes 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.
Special applications are advantageous in highly dynamic websites.
14. Simplify the page with HTML5 and CSS 3.0来
HTML5 includes new structural elements, such as header,nav,article and footer, that use these semantic elements to make the page simpler and easier to parse than the traditional use of div and span tags, and a simple page to load faster, and the Simple Dom (Document Object Model) represents faster JavaScript execution efficiency, and new tags can be quickly applied to new browser versions including mobile, 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. The autofocus attribute is used to indicate which input box should be automatically positioned.
There are also some new input-box elements that can be used without javascript to accomplish some common requirements, such as E-mail,url, numbers, ranges, dates and times that require complex user interaction and input validation elements, on mobile browsers, When you need to enter text, the keyboard that pops up is usually selected by a particular type of input box, and a browser that does not support the specified input type displays 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 are originally loaded with images, so that these new features can speed up page rendering.
Making these changes manually is very complex and time-consuming, and if you use a CMS, it can help you generate many HTML and CSS that you don't need to control (see the Ma Haixiang blog, "Tips for optimizing SEO techniques in the process of making mobile phone sites").
15. Delay Rendering "below-the-fold" content
It is certain that if we delay loading the contents of the invisible area, then the page will be displayed more quickly in front of the user, this area is called "below the fold", in order to reduce the content that needs re-access after the page loads, can replace the picture with the correct aspect marked Label.
Some good JavaScript libraries can be used to handle these below-the-fold lazy loading images.
16. Deferred read and execute scripts
On some mobile devices, parsing JavaScript code can take up to 100 milliseconds per gigabyte, and many script libraries are not loaded until the page is rendered, and 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 before the user sees the page, and the same logic can be applied to the script execution, as much as possible after the execution of the script is deferred to the OnLoad event, rather than when it is important to the user to see the content in the initialization page.
These delayed scripts may be written by yourself, and more importantly, possibly third-party, poor scripting optimizations for ads, social media parts, or analytics can result in blocking page rendering, adding valuable load times, of course, You need to carefully evaluate a large scripting framework such as jquery, which is designed for mobile web sites, especially when you are simply using some objects in these frameworks.
Many third-party frameworks now provide an asynchronous version of an API that delays loading, and developers simply need to translate the original logic into this asynchronous version, and some JavaScript will be somewhat more complicated to delay loading because it takes a lot of attention to execute these scripts after onload (for example, 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.
17. Use Ajax to enhance the process
Ajax (asynchronous JavaScript and XML) is a technology that uses XHR (XMLHttpRequest) objects to get data from a Web server, and it doesn't need to update a running page. Ajax can update a part of a page without having to rebuild the entire page, which 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, but XMLHttpRequest does not force you to 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 technology, to ensure that your Ajax return response using the cache header, simplification, gzip compression, resource consolidation and other technologies.
Because this technology is different depending on the application, it is difficult to quantify, perhaps due to cross-domain issues, you need to use XHR2, the technology can use the resources of the external domain, so as to be able to cross-domain XHR request.
18, according to network conditions to adapt to the processing
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, and the server detects the network condition of your application by detecting the User-agent header or other information embedded in the request.
The API for detecting network information has recently changed, and the interface is now not directly defining network conditions such as wi-fi,3g, but rather gives bandwidth information and recommendations such as "very slow, slow, fast and very fast", with a property that gives an estimated MB/s value and a "Meterd" Boolean value to indicate its credibility, but it is difficult for the browser to judge the environment, judging the current network environment and then adaptation is still the best method (see the Ma Haixiang Blog "Baidu Mobile search open adaptation service 3 methods" of the relevant introduction), But this method is being considered to be replaced.
19. Use the HTML5 Web Worker feature for multithreading
The web worker in HTML5 is using multiple threads to execute JavaScript programs concurrently, and this particular multithreaded implementation can reduce problems that have puzzled developers for years and on other platforms, such as when a thread needs to change 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 the performance of mobile sites, the code in the Web worker is well suited to preprocess the resources needed for further operations, especially if the user's bandwidth resource is not scarce, too much preload may interfere with the UI response of the current page in the case of a low-processor-performance mobile device. 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.
Specifically, the Web worker is only available on Android 2.0 and above, and the previous version of iOS5 on the iphone is not supported, and on desktop PCs, always behind IE only in IE 10 support Web worker.
Although this technology is not very difficult to implement, but for web workers, there are some restrictions that need to be enforced, the web workers not go into the dom of the page, and can not change anything on the page, WEB worker is suitable for the kind of work that requires background computation and processing.
20. 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 and the device uses about half a second (most devices are almost 300 milliseconds) to determine whether it is a gesture or a click, which can significantly affect the user's desired response performance. To be resolved by using the Touchend event, the event is immediately triggered when the user touches the screen.
In order to ensure that the user does not expect the behavior, you should also use the Touchstart and Touchmove events, for example, unless there is also a Touchstart event on the button, do not judge the Touchend event on the button means that the click behavior , since the user is likely to touch from somewhere else and then drag to the end of the button, you can also use the Touchmove event after the Touchstart event to avoid mistaking the Touchend event for a click, The premise, of course, is to assume that a drag gesture is not intended to generate click behavior.
In addition, you also need to handle the OnClick event to let the browser change the appearance of the button to identify the state as clicked, and you also need to handle those browsers that do not support touch events, in order to avoid the code in the Touchend and the onclick code repeated execution, You need to call the Preventdefault and Stoppropagation methods in the Click event after making sure that the user touches the event already executed in Touchend.
This technique requires more work to add and maintain links in a single page, and the code for the touch event must consider other gestures, since replacing the click may also be a scaling or tapping action.
21. 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, and in 2009, Google began developing a protocol called Spdy ("speedy") to replace existing agreements that claim to be able to break through these limits, The goal of this protocol is to allow multiple browsers and a variety of Web services to support, 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 support Spdy, Then all the sites above it can interact with the browser that supports this protocol and use Spdy to apply Spdy to 25 top100 Internet sites, and Google collects data that is 27% to 60% faster than the website.
Spdy automatically uses gzip to compress all content, unlike HTTP, which uses GZIP compression for header data, Spdy uses multithreading technology to allow multiple request streams or response streams to share a single TCP connection, and Spdy allows requests to set priorities, for example, The video in the center of the page will have a higher priority than the border ads.
Perhaps the most transformative invention in spdy is that the flow is bidirectional and can be initiated by the client or the server, so that the information can be pushed to the client instead of the first request by the client, for example, when a user first browses a site and does not have any cache of the site, This time the server can push all the request resources in the response, instead of waiting for each resource to be re-requested again, as a replacement protocol, the server can send a hint to the client, prompting the page what resources are needed, and also allowing 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.
Based on the site and the service environment for smooth operation or further consideration, Google has a spdy module support apache2.2–mod_spdy– This module is free, but mod_spy the problem on the thread, and mod_php collaboration is not very good, So ask you to use this technology when you want to make sure that your site is working properly.
Ma Haixiang Blog Comments:
If the lack of continuous and careful test reminders, performance optimization is just a discussion, is not complete, if you do not specify a benchmark to do the comparison, any changes in your system is only a theory, if there is no real test data, guess the bottleneck of performance is meaningless.
There are many open source and common tools for integration testing and for different geographies and bandwidth/latency testing, and the RUM (real user monitoring) tool can turn a test environment from a lab into an unpredictable, real user behavior.
Looking at the test options for mobile devices and desktop scenarios, if you are choosing an automated solution, be sure to use a solution that can continue to test and differentiate the changes before and after the application optimization method.
If performance optimization is only a step in the development process, it will not have any effect, it must become part of a continuous improvement site.
This article for Ma Haixiang Blog original article, if want to reprint, please indicate the original site from the http://www.mahaixiang.cn/ydseo/1198.html, annotated source, otherwise, no reprint; Thank you!
Tips for optimizing page load performance for mobile web sites