Html5 performance
-
date post
12-Sep-2014 -
Category
Technology
-
view
1.001 -
download
1
description
Transcript of Html5 performance
Mobile HTML5 Performance
Optimizing web applications for the mobile web
Stefan Comanescu (@faq2010)January 2012
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)
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)
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)
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
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
• 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 ?
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
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
● 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 ?
● 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
● 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Geolocation
navigator.geolocation.getCurrentPosition(
handlePosition, handleError, options
);
Function handlePosition(coords){
// do something with coords.latitude / longitude /
position / accuracy / heading / speed / timestamp
}
HTLM5 Performance Optimizations
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
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
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
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
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
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
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
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
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
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
More info, details and examples on http://bit.ly/ySMxqv
Stefan Comanescu (@faq2010)January 2012
Websites
● http://html5doctor.com/
● http://diveintohtml5.info/
● http://www.html5rocks.com/en/
● http://html5demos.com/
Ebooks
● Introducing HTML5
● HTML5: Up and Running
Some good HTML5 resources