Html5 performance

52
Mobile HTML5 Performance Optimizing web applications for the mobile web Stefan Comanescu (@faq2010) January 2012
  • date post

    12-Sep-2014
  • Category

    Technology

  • view

    1.001
  • download

    1

description

 

Transcript of Html5 performance

Page 1: Html5 performance

Mobile HTML5 Performance

Optimizing web applications for the mobile web

Stefan Comanescu (@faq2010)January 2012

Page 2: Html5 performance

How important is the mobile web ?

01/2010 02/2010 03/2010 04/2010 05/2010 06/2010 07/2010 08/2010 09/2010 10/2010 11/2010 12/2010 01/2011%

1%

2%

3%

4%

5%

6%

7%

8%

9%

Traffic

Mobile traffic in the UK (Jan 2010 – Jan 2011)

Page 3: Html5 performance

How important is the mobile web ?

Percentage of people accessing the internet in China (Jan 2008 – Jun 2009)

Jan 2008 Jan 20090%

10%

20%

30%

40%

50%

60%

70%

80%

90%

100%

Desktop

Mobile phone

Laptop

Other

Source: Statistical Report on Internet Connection in China (www.ccnic.cn)

Page 4: Html5 performance

How important is the mobile web ?

Average percentage traffic from mobile devices (147% increase)

January 2010 January 20110%

20%

40%

60%

80%

100%

120%

Mobile Traffic

Desktop traffic

Source: average percentage of traffic across 40 sites (freshegg.com)

Page 5: Html5 performance

How important is the mobile web ?

Global mobile data traffic growth estimation

2010 2011 2012 2013 2014 20150

1

2

3

4

5

6

7

Exabytes

Source: Cisco February 2011

Page 6: Html5 performance

How important is the mobile web ?

Effective cost per MB - smartphones

Q1 2010 Q2 2010 Q3 2010 Q4 2010 Q1 20110

0.02

0.04

0.06

0.08

0.1

0.12

0.14

0.16

$

Source: Nielsen

Page 7: Html5 performance

• Mobile internet usage is growing faster than anticipated

and it will eventually surpass desktop internet usage; some

say this will happen as soon as 2014.

• Mobile data plans are getting cheaper, but they will never

be free, nor unlimited (because traffic would be too high

and because cell carriers are afraid of VoIP).

How important is the mobile web ?

Page 8: Html5 performance

How are mobile devices evolving ?

Source: Nielsen

Smartphone penetration in the US

Q2 08 Q3 08 Q4 08 Q1 09 Q2 09 Q3 09 Q3 09 Q4 09 Q1 10 Q2 10 Q3 10 Q4 10 Q1 11 Q2 110

10

20

30

40

50

60

70

80

90

100

Feature phones

Smartphones

Page 9: Html5 performance

2008iPhone 3G

412 mhz ARM11128 mb RAM

PowerVR MBX

2011iPhone 4S

Dual-core 1GHz512 mb RAM

PowerVR SGX543

How are mobile devices evolving ?

Apple iPhone – 2008 vs 2011

Page 10: Html5 performance

● Sony is phasing out feature phones after buying out Ericsson's

shares

● Nokia is developing another homebrew OS to replace it's line of

feature phones (S40), presumably named 'Meltemi OS'

● In conclusion, the smartphone killed the feature phone; hardware on

mobile devices is evolving fast but it still is a lot slower than that of

your average PC

How are mobile devices evolving ?

Page 11: Html5 performance

● Besides the diversity of form factors, the greatest problem in

developing mobile applications is the diversity of operating systems

they run on.

● Because the hardware is so diverse the best way to target multiple

devices is to add an abstraction layer and this common abstraction

layer that all the mobile operating systems support is HTML5.

Developing mobile apps

Page 12: Html5 performance

● HTML5 apps can be used on mobile devices inside browsers or they

can have the look and feel of a native app by using a 'web view'

control and routing the Javascript calls to a native API.

● Obviously, performance on CPU intensive apps is lower on HTML5,

but how much lower depends on the smart usage of the features that

HTML5 provides.

Developing mobile apps

Page 13: Html5 performance

The async and defer attributes

● These attributes can be assigned to scripts so that they are not

evaluated when they are parsed, not blocking the rendering of the

page.

● Defer was also available in HTML4, it tells the user agent to continue

parsing and rendering because the script doesn't generate content,

whilst the async tag tells the browser to load scripts asynchronously,

in a non-blocking manner.

HTLM5 Performance Optimizations

Page 14: Html5 performance

The async and defer attributes

<script async src="async.js"> </script>

<script defer src="defer.js"> </script>

● As the name implies, the difference between them is that async

scripts execute as soon as they are loaded, so the order in which

they are execute is unknown; whereas defer scripts are executed in

order.

HTLM5 Performance Optimizations

Page 15: Html5 performance

Minification

● Minification removes all unnecessary characters from your scripts,

like whitespace, comments or variable names that are too long, so

that you can get a smaller file download

● YUI Compressor reportedly reduces your code by up to 60%,

http://developer.yahoo.com/yui/compressor/

HTLM5 Performance Optimizations

Page 16: Html5 performance

Minification

java -jar yuicompressor script.js -o script-min.js

JQuery 1.7.1 (242KiB) > jQuery 1.7.1-min (102KiB)

Jquery Mobile 1.0 (209KiB) > jQuery Mobile 1.0-min (83KiB)

MooTools 1.4.2 (143 KiB) > MooTools 1.4.2-min (86KiB)

HTLM5 Performance Optimizations

Page 17: Html5 performance

Gzip compression

● Gzip enables you to compress data sent from the web server, most

browsers (including mobile browsers) have support for gzip

decompression

● Decompressing gzipped data is not expensive, meaning that it

doesn't have any impact on the slower CPUs of mobile devices

HTLM5 Performance Optimizations

Page 18: Html5 performance

Gzip compression

gzip script.js

JQuery 1.7.1-min (102KiB) > jQuery 1.7.1-min.gz (31KiB)

Jquery Mobile 1.0-min (83KiB) > jQuery Mobile 1.0-gz (25KiB)

MooTools 1.4.2-min (86 KiB) > MooTools 1.4.2-gz (27KiB)

HTLM5 Performance Optimizations

Page 19: Html5 performance

Combined files

● Browsers can perform a limited number of parallel connections per

server, so they should be used wisely. Combining script or css files,

although obviously generating a larger file gives us a faster download

time, by reducing the number of required connections.

HTLM5 Performance Optimizations

Page 20: Html5 performance

Code caching

● There are operations, like loops for example, where there is no need

to access an element on every iteration, it's much better to assign the

element to a variable outside the loop.

● It's a good idea to store the accessed DOM elements and when

needed again to access them from the local data structures, and not

by accessing the DOM again.

HTLM5 Performance Optimizations

Page 21: Html5 performance

Code caching

for(var i=0; i<$('section').length; i++) {

$('section')[i].hide();

}

Var sections = $('section'), len = sections.length;

for(var i=0; i<len; i++) {

sections[i].hide();

}

HTLM5 Performance Optimizations

Page 22: Html5 performance

Better selectors

● Try to select by 'id' whenever possible.

● The selector engine searches the DOM from right to left meaning

that we should be specific to the selectors that are in the right side of

the selection and the left side should be as limited as possible.

HTLM5 Performance Optimizations

Page 23: Html5 performance

Dynamically apply styles

● When styling many elements avoid changing the style for every

element, one at a time, like element.style(...) or element.css (if using

jQuery); it's better to append a stylesheet to the page with all the

required changes.

HTLM5 Performance Optimizations

Page 24: Html5 performance

Ajax

● For a better user experience and because network latency is so

important for mobile devices, use Ajax as often as possible.

● XMLHttpRequest Level 2 offers extended functionality, including

progress events, cross-site requests and handling of byte streams,

things that make a web application look more like a native

application.

HTLM5 Performance Optimizations

Page 25: Html5 performance

Application cache

● Keep as much data as possible on the client, HTML5 application

cache let's us specify which files should the client store locally,

through a manifest file that is pointed out by a 'manifest' attribute

included in the html tag.

● The manifest file can also specify files that require the user to be

online and fallback files for when he's offline.

HTLM5 Performance Optimizations

Page 26: Html5 performance

Application cache

<html manifest=”basic_offline.manifest”>

basic_offline.manifest:

CACHE MANIFEST

#version 1

index.html

contact.html

style.css …

HTLM5 Performance Optimizations

To refresh the user's offline files

change some content

in the manifest file

e.g. the version number

Page 27: Html5 performance

Webstorage (Local Storage & Session Storage)

● Webstorage is ideal for easy key – value storage and retrieval

● Data stored in webstorage is not sent back to the server at every

request, like it does in cookies, thus, diminishing network traffic

● Webstorage has a much higher capacity then cookies, cookies can

store 4kb whereas webstorage can store 5Mb per domain or even

more on certain browsers (e.g. 10Mb on IE)

HTLM5 Performance Optimizations

Page 28: Html5 performance

Webstorage (Local Storage & Session Storage)

● Session storage and localstorage use the same API, but session storage

stores data only for the current session.

localStorage.setItem('user_id', 123);

var user_id = localStorage.getItem('user_id');

localStorage.removeItem('user_id');

localStorage.clear();

HTLM5 Performance Optimizations

Page 29: Html5 performance

Web SQL Databases

● Web Databases are client-side databases, meaning they are

persistent in the user's browser

● Specification is based around SQLite

HTLM5 Performance Optimizations

Page 30: Html5 performance

Web SQL Databases

● There are 3 core methods:

● openDatabase: For creating the database object.

● transaction: For controlling a transaction and performing either

commit or rollback.

● executeSql: For executing SQL queries.

HTLM5 Performance Optimizations

Page 31: Html5 performance

Web SQL Databases

Var size = 5*1024*1024,

database = openDatabase(“dbName”, “1.0”,”Description”, size)

● If the size is larger than 5MB, depending on the implementation, the user

might be prompted to allow the scaling of the database.

HTLM5 Performance Optimizations

Page 32: Html5 performance

Web SQL Databases

db.transaction(function (tx) {

tx.executeSql('CREATE TABLE IF NOT EXISTS test (id unique,

text)');

});

● Operations are made in a transactions, because if one operation fails, the

transaction wouldn't take place (it would rollback all previous operations that

succeeded)

● tx is the transaction object

HTLM5 Performance Optimizations

Page 33: Html5 performance

Websockets

● Websockets offer a low latency full-duplex communication channel

● There is no longer a need to have multiple ajax requests or comet

long polling for real time communication; methods that feel unnatural

and use more bandwidth (because of the HTTP overhead)

● Websockets allow cross origin communication

● It can be used in all of today's major browsers, but it may be disabled

by default in some, because of previous security vulnerabilities.

HTLM5 Performance Optimizations

Page 34: Html5 performance

Websockets

var ws = new WebSocket('ws://localhost:8080/socket');

ws.onopen = function() {console.log('Connected');}

ws.onmessage = function(msg)

{console.log('received ' + msg);}

ws.send(“test”);

ws.close();

HTLM5 Performance Optimizations

Page 35: Html5 performance

Server Sent Events (SSE)

● Just like websockets, SSE can push data to the browser, but unlike

websockets, it doesn't offer a bidirectional message channel, it's for

situations where the client needs a stream of updates

● Unlike websockets, SSE doesn't require a special server/protocol, it

uses plain HTTP

● SSE also has the capability to reconnect if the connection is lost

HTLM5 Performance Optimizations

Page 36: Html5 performance

Server Sent Events (SSE)

var stream = new EventSource('events/news.py');

stream.addEventListener('open' ,function() {...});

stream.addEventListener('message' ,function(e) {

console.log(e.data);

});

stream.addEventListener('error' ,function() {...});

HTLM5 Performance Optimizations

Page 37: Html5 performance

Webworkers

● Webworkers are background threads

● Used for handling CPU intensive tasks

● They help keeping the UI responsive while doing calculations

● Webworkers can't do DOM manipulation, or access the window or

documents objects (it's not thread-safe)

HTLM5 Performance Optimizations

Page 38: Html5 performance

Webworkers

var worker = new Worker('worker_script.js');

Worker.onmessage = function(e){

Console.log('received ' + e.data);

}

stream.addEventListener('message' ,function(e) {

console.log(e.data);

});

stream.addEventListener('error' ,function() {...});

HTLM5 Performance Optimizations

Page 39: Html5 performance

Geolocation

● To find out the location of the client there is no longer required to

inspect the client's IP address and give a “very approximate” answer

● Geolocation provides an easy API for detecting the user's position

based on GPS, signal on certain cell towers, and lastly IP address

HTLM5 Performance Optimizations

Page 40: Html5 performance

Geolocation

navigator.geolocation.getCurrentPosition(

handlePosition, handleError, options

);

Function handlePosition(coords){

// do something with coords.latitude / longitude /

position / accuracy / heading / speed / timestamp

}

HTLM5 Performance Optimizations

Page 41: Html5 performance

CSS3 Transitions

● CSS3 transitions replace Javascript animations and provide a much

smoother experience, because they are directly handled by the GPU.

We just provide an end states and the browser handles all the

hardware acceleration optimizations.

HTLM5 Performance Optimizations

Page 42: Html5 performance

CSS3 Transitions

$('#btn').click(function(){

$('#panel').animate({opacity:0}, 2000, 'easein');

$('#panel').css('opacity', 0);

})

#panel{

-o-transition: opacity 2s ease-in;

}

HTLM5 Performance Optimizations

Page 43: Html5 performance

CSS3 Transforms

● Transforms allows us to modify elements like previously possible only with

Javascript, SVG or Canvas.

#id {

transform: scale(5, 2) translate(43px, 55px) transform:

rotate(45deg);

}

HTLM5 Performance Optimizations

Page 44: Html5 performance

Sprites

● Sprites are large images that contain smaller icons, that enable us to

do a single file download and use this same file whenever we need to

display an icon, by displaying just a portion of the sprite (think

overflow:hidden and left:x top:y).

● A good web service for creating spirtes and the corresponding CSS is

http://spritegen.website-performance.org/

HTLM5 Performance Optimizations

Page 45: Html5 performance

CSS3 goodies

● There is no longer a need for pictures that display rounded corners,

box shadows or gradients, they are all available in CSS3, some with

vendor prefixes for the moment

● e.g

background: -moz-linear-gradient(top, black, white);

box-shadow: 2px 2px 5px #222;

border-top-left-radius: 5px;

HTLM5 Performance Optimizations

Page 46: Html5 performance

CSS3 goodies

● @font-face enables us to define custom fonts to use on our web

applications, there is no need to use pictures just for displaying fancy fonts.

@font-face{

font-family: thefont;

src: url('fonts/thefont.otf'),

url('fonts/thefont.eot'); // for internet explorer

}

HTLM5 Performance Optimizations

Page 47: Html5 performance

CSS3 goodies

● There is no longer a need for pictures that display rounded corners,

box shadows or gradients, they are all available in CSS3, some with

vendor prefixes for the moment

● e.g

background: -moz-linear-gradient(top, black, white);

box-shadow: 2px 2px 5px #222;

border-top-left-radius: 5px;

HTLM5 Performance Optimizations

Page 48: Html5 performance

CSS3 Media Queries

● With CSS3 Media Queries you can easily target multiple devices,

taking into account their width, height, orientation and resolution.

● e.g.

@media only screen and (max-device-width: 320px) {

}

HTLM5 Performance Optimizations

Page 49: Html5 performance

CSS3 Selectors

● CSS3 selectors enables us to target elements at a more granular

level, so we can avoid applying stylesheets to specific elements using

Javascript. The markup can now be slim, semantic and flexible.

HTLM5 Performance Optimizations

Page 50: Html5 performance

CSS3 Selectors

tr:nth-child(odd) #for creating zebra tables

nth-of-type #nth-child with specified type

input:not([type=”number”]) #every other input

a[href*="google"] #links that contain “google” in href

a[href^="http://"] #links that start with http

a[href$=".info"] #links that end with .info

HTLM5 Performance Optimizations

Page 51: Html5 performance

More info, details and examples on http://bit.ly/ySMxqv

Stefan Comanescu (@faq2010)January 2012