Mobile site speed optimization

    Along with the growth of mobile Internet, the need to optimize the speed of mobile sites is growing. Even the most modern smartphones on Android, iOS, WebOS, BlackBerry OS, etc. have processors with a frequency of not more than 1Ghz, and 3G speeds can be considered quite slow (download speed is 3 times lower than DSL).

    Mobile devices have inherited the problems of “large” machines: from the number of http requests to JavaScript performance.

    Mobile Features


    Besides the fact that they often fit in your pocket and are easier to lose, there are several key differences between mobile devices and desktops:
    • low screen resolution;
    • slow connections;
    • limited cache size;
    • many different devices and form factors;
    • low processor power;
    • Extensive HTML5 support
    • relatively new browsers (they don’t know about IE6 in this world).


    General recommendations


    Most of the performance problems of “large sites” are inherent in mobile sites, so many of these techniques come from desktop optimization.
    • use gzip to compress text data;
    • put CSS in the heading of the HTML document, and JavaScript at the bottom of the page;
    • Combine JavaScript and CSS files that are used throughout the site. This will reduce the number of HTTP requests, which is extremely critical for mobile sites;
    • Use minimization and obfuscation of CSS and JavaScript code;
    • JS and CSS that are used only 1 time on the site, as well as small JS and CSS (up to 5 kB), it is better to include directly in the page, i.e. Do not put in separate files;
    • many mobile browsers (for example, Android or Opera Mobile) have a general limit on the number of connections not more than 4-6. Using domain sharding for such browsers can only harm the speed of the site;
    • at the same time, the Android browser supports HTTP pipelining, which allows you to send 3 requests to the server at once in one connection. Remember to make sure that the server also supports HTTP pipelining;
    • it is very important to compress files correctly (without visible loss in quality) - use, for example, Smush.it - more on this ;
    • Avoid or at least cache redirects.
    • for iOS, use Quicktime Reference Movies, this allows you to “give” the visitor different video files, based on the capabilities of his Internet connection.
    • Take advantage of WebSockets wherever possible (full support is available only in iOS Safari 4.2-4.3, partial in Opera Mobile 11.1).

    HTML and CSS optimization


    Extensive support for HTML5 and CSS3 in mobile browsers allows you to use the most modern techniques for website optimization:
    • HTML code should be extremely simple. Use HTML5 semantic elements, specify, exclude optional xmlns attributes. Also try to reduce the number of divs and classes;
    • try to use input less often, and if to use, then in HTML5 formats;
    • use CSS gradients instead of background images - this will drastically reduce the number of calls to the server;
    • CSS provides many other useful features, the use of which is more effective than images (shadows, rounded borders, multiple backgrounds embedded in the svg and canvas page).

    Image optimization


    Along with the fight against unnecessary calls to the server, it is very important to minimize the size of the downloaded files. In this perspective, image optimization is the most important element.
    • Use CSS sprites to optimize logos and icons;
    • in html and css encode images in base64 - a very efficient way, because It is supported by most mobile browsers, and encoding takes place on the server side. In addition to PHP - base64_encode (), you can use HTML5 technology from Canvas - toDataURL ();
    • encode Emoji icons in Unicode instead of images (supported since iOS 2.2, as well as in many Japanese phones);

    On mobile devices, screens have significantly lower resolution than desktop screens. CSS allows us to determine the current resolution of the user's screen and, depending on this, give him that version of the picture that has a more suitable resolution.

    /* Screens bigger than 480px */
    @media only screen and (min-device-width: 481px) {
    #header { background-image: url(header-full.png); }
    }

    The code above determines that the user’s screen width is greater than 480px and instructs the browser to download the header-full.png picture with full resolution.
    But the following code fragment, determining that the screen width is less than 480px, offers the browser a picture adapted for small screens:

    /* Screens smaller than 480px */
    @media only screen and (max-device-width: 480px) {
    #header { background-image: url(header-small.png); }
    }

    As a result of this understanding between the site and the browser, the size of the data downloaded to the mobile device will decrease significantly.

    However, first of all, take care of user convenience. Using the same principle (separate content for mobile and desktop devices), you can make the site enjoyable for users with high-resolution screens, while at the same time not harming other visitors.
    For example, iPhone 4 users are already accustomed to having high DPI images (e.g. 300) on their phone screen. And if you want your site to look poor on Retina screens, you will need to prepare another separate set of high-resolution images and upload them using CSS Media Queries

    /* High dpi */
    @media only screen and (min-resolution: 300dpi),
      only screen and (-webkit-min-device-pixel-ratio: 1.5),
      only screen and (min--moz-device-pixel-ratio: 1.5) {
    #header { background-image: url(header-300dpi.png); }
    }
    /* Low dpi */
    @media only screen and (max-resolution: 299dpi),
      only screen and (-webkit-max-device-pixel-ratio: 1.5),
      only screen and (max--moz-device-pixel-ratio: 1.5) {
    #header { background-image: url(header-72dpi.png); }
    }

    This is exactly the case when it is worth sacrificing performance in favor of user convenience.

    Connection Speed ​​Optimization


    Starting with Android 2.2 Froyo, developers have the opportunity to receive data on the current type of Internet connection from the device. This is implemented using the navigator.connection object.

    Here is an example of data received from a device that works in a 3G network: Connection type “4”, which corresponds to CELL_3G. Using a simple script, you can determine the type of connection and pass this information as a CSS class in the HTML element.

    navigator = {
    connection: {
    "type": "4",
    "UNKNOWN": "0",
    "ETHERNET": "1",
    "WIFI": "2",
    "CELL_2G": "3",
    "CELL_3G": "4"
    }
    };



    // Initialize variables
    var connection, connectionSpeed, htmlNode, htmlClass;
    // Create a custom object fallback if navigator.connection isn't available
    connection = navigator.connection || {'type':'0'};
    // Set connectionSpeed
    switch(connection.type) {
    case connection.CELL_3G:
      // 3G
      connectionSpeed = 'mediumbandwidth';
    break;
    case connection.CELL_2G:
      // 2G
      connectionSpeed = 'lowbandwidth';
    break;
    default:
      // WIFI, ETHERNET, UNKNOWN
      connectionSpeed = 'highbandwidth';
    }
    // set the connection speed on the html element, i.e. 
    htmlNode = document.body.parentNode;
    htmlClass = htmlNode.getAttribute('class') || '';
    htmlNode.setAttribute('class', htmlClass + ' ' + connectionSpeed);

    As a result, when defining a low-speed connection, we pass optimized images using CSS to the visitor’s browser:

    .highbandwidth .logo   { background-image:url('logo-high.jpg'); }
    .mediumbandwidth .logo { background-image:url('logo-medium.jpg'); }
    .lowbandwidth .logo    { background-image:url('logo-low.jpg'); }


    And yet, you should not deprive users of choice (we will not be dictators). Therefore, in addition to the common choice:
    • site version desktop | mobile

    Give also a choice:
    • connection speed: High | Medium | Low

    Use simple rules - “if pixels are not visible, they do not need to be downloaded”, but at the same time “you should not decide for the user, you can recommend him”.

    Caching


    If in the case of desktops in most cases the solution will be in favor of external files, then with mobile it is most likely the opposite. Due to the small size of the cache, there is no need to talk about large and long-term savings. There are a number of tips for optimizing page reload speed:
    • cache ajax;
    • set the headers of the relevance of files for the distant future (far-future cache expiration headers);
    • avoid cookies, use localStorage instead (cookies are transmitted by http requests, significantly increasing the size of the data transferred). LocalStorage and SessionStorage are HTML5 technologies that are a more effective alternative to cookies. External CSS and JavaScript can also be stored there;

    An important limitation for LocalStorage and SessionStorage is that they can only store data of type String. Therefore, you should first translate the data into a string format, and subsequently restore it to the original using JSON.stringify()and JSON.parse():

    var user = {
      firstName: 'Joe',
      lastName: 'Schmoe',
      age: 40
    }
    // Store the object
    localStorage.userInfo = JSON.stringify(user);
    // Retrieve the object
    var user = JSON.parse(localStorage.userInfo);

    The sizes of the data that can be stored in these objects vary from browser to browser, but 5 Mb should be enough for most.
    An interesting point - devices on Android and BlackBerry OS can store the cache even after turning on / off the device, at the same time, the iPhone can not boast of this.
    SmartphonesiPhone 4Galaxy SNexus sBlackberry torch
    OS / VeriOS / 4.3Android 2.2Android 2.3Blackberry 6
    Constant*04425
    In mind**1004425
    TabletsiPad 1iPad 2XOOM
    OS / VeriOS / 4.3iOS / 4.3Android 3.0
    Constant*0020
    In mind**20fifty20
    * Persistent - this is the cache that remains, even after restarting the browser.
    ** In memory is a cache that is stored in RAM (for example, when switching between applications). Read more about the cache on mobile devices on the Blaze blog .

    Javascript optimization


    Insufficient processor power in mobile devices, once again makes the struggle to reduce the load relevant. So Google’s research shows that parsing every 1KB of JavaScript code is about 1ms.
    • avoid javascript timeout animations, it’s better to use CSS3 transitions instead (but not all browsers fully support this technology, so you should have a “spare” old-school option for this case)
    • on touch devices, click handlers lead to a delay of 300-500 ms, which is quite a lot, therefore it is better to use “native” handlers for such devices - ontouchend;
    • use only the necessary parts of large frameworks (e.g. jQuery), not the whole of them. It will be even more optimal to use small frameworks (XUI, zepto.js, microjs);
    • strive to minimize javascript in forms, it is better to use HTML5, where possible;
    • Another useful achievement of HTML5 is the use of databases that are stored on the client side. Among the existing solutions, indexedDB got the most popularity (we hope that soon this technology will be supported by mobile browsers);
    • use ajax (onhashchange - for managing history) and request only what needs to be changed;
    • download JS asynchronously to the main content;
    • reduce starting delays. For example, the Gmail Mobile team has proposed an interesting way to “lazy” load modules ;
    The essence of this method is that first you need to break large program modules into smaller ones and distribute which of them need to be loaded at the start of page loading, and which later. It is also important that pending modules will be loaded as they are called by user actions. Such a download really looks lazy: until you kick, it won’t move.

    Conclusion


    The importance of optimizing the speed of mobile sites is becoming more important now that users are increasingly using smartphones to solve everyday tasks on the Internet.

    Interestingly, most people are more intolerant of the slow operation of sites when using smartphones. Often this is due to specific tasks that need to be solved within a few seconds (for example, specify the address of the restaurant).

    It is important to remember that our task is to minimize the website loading speed with the least loss in functionality and usability.

    Also popular now: