html5 refresher
DESCRIPTION
Mobile applications Development - Lecture 10 HTML5 Refresher This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy). http://www.di.univaq.it/malavoltaTRANSCRIPT
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers
Intro
HTML5 is potentially the first true crosscrosscrosscross----platformplatformplatformplatformapp technologyapp technologyapp technologyapp technologyapp technologyapp technologyapp technologyapp technology
Intro
HTML5 will be the new standard for HTML
HTML5 is still a work in progresswork in progresswork in progresswork in progressW3C final recomendation: 2020
Top browsers Top browsers Top browsers Top browsers support many (not all) of the new HTML5 elementselements
http://mobilehtml5.orghttp://caniuse.com
What is HTML5?
It is an extension of HTML/XHTML 4
• with new more semantically rich elementswith new more semantically rich elementswith new more semantically rich elementswith new more semantically rich elements– <article>, <footer>, <header>, <nav>, <section>
• deprecating tags & attributesdeprecating tags & attributesdeprecating tags & attributesdeprecating tags & attributes– <center>, <font>, <frame>, height, width
• introducing new attributesintroducing new attributesintroducing new attributesintroducing new attributes• introducing new attributesintroducing new attributesintroducing new attributesintroducing new attributes– placeholder, form
• additionaladditionaladditionaladditional APIsAPIsAPIsAPIs– geolocalization, video, audio
The HTML5 creation rules
• New features should be based on HTML, CSS, and JSHTML, CSS, and JSHTML, CSS, and JSHTML, CSS, and JS
• Reduce the need for external external external external pluginspluginspluginsplugins (like Flash)
• Better error handlingerror handlingerror handlingerror handling– ignore unknown stuff and move on
• More markup to replace scriptingreplace scriptingreplace scriptingreplace scripting• More markup to replace scriptingreplace scriptingreplace scriptingreplace scripting
• Avoid deviceAvoid deviceAvoid deviceAvoid device----specific specific specific specific profiling
• Make the process openprocess openprocess openprocess open
The minimal HTML5 page
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body><body>
…
</body>
</html>
The HTML5 Doctype
It must be the first thing in your HTML5 document, before the <html> tagbefore the <html> tag
It is an instruction to the web browser instruction to the web browser instruction to the web browser instruction to the web browser about what version of HTML the page is written in
HTML 4 Doctype declarations required a reference HTML 4 Doctype declarations required a reference to a DTD, because HTML 4 was based on SGML
(Standard Generalized Markup Language)
HTML5 VS XHTML 4
• HTML5 will allow both quick-closing of empty tags • HTML5 will allow both quick-closing of empty tags but you can use those elements just as well without quick-closing them<input type=“text”>
<input type=“text” />
• quotes for attributes are optional<a href=http://www.google.com>
HTML5 VS XHTML 4
• you can use upper-case letters for your element names<DIV>hello</DIV><DIV>hello</DIV>
• No need to specify the type of script elements if it isJavascript<script src=“test.js”>
• No need to specify the type of style elements if it isCSS<link rel="stylesheet" href="style.css“>
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers
New Structural Tags
Main Goal: separate separate separate separate presentationpresentationpresentationpresentation fromfromfromfrom contentcontentcontentcontent
• Poor accessibility• Unnecessary complexity• Larger document size
Most of the presentational features from earlier versions of HTML are no longer supported
New Structural Tags
<header> header region of a page or section
<footer> footer region of a page or section
<nav> navigation region of a page or section
<section> logical region of a page<section> logical region of a page
<article> a complete piece of content
<aside> secondary or related content
Other Structural Tags
<command> a command button that a user can invoke<details> additional details that the user can view or
hide<details> additional details that the user can view or
hide<summary> a visible heading for a <details> element<meter> an amount within a range<progress> shows real-time progress towards a goal<figure> self-contained content, like illustrations,
diagrams, photos, code listings, etc.diagrams, photos, code listings, etc.<figcaption> caption of a figure<mark> marked/highlighted text<time> a date/time<wbr>Defines a possible line-break
Custom Data Attributes
Can be used to add metadatametadatametadatametadata about any element withinan HTML5 pagean HTML5 page
They are ignored by the validator for HTML5 documents
They all start with the data- pattern
TheyTheyTheyThey can can can can bebebebe readreadreadread bybybyby anyanyanyany browser browser browser browser using Javascript via the getAttribute() method
In-place Editing
This feature is provided by defining the contenteditableattributeattribute
Any elements with the contenteditable attribute set will have a grey outline as you hover
Performed changes can be saved via Javascript
<section id="editable“ contenteditable="true"> hello
</section>
var editable = document.getElementById('editable');
editable.innerHtml
Sandbox attribute for iframes
Method of running external site pages with reduced privileges reduced privileges reduced privileges reduced privileges in iframesin iframes
<iframe src=“other.htm" sandbox=""></iframe>
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers
Forms
Main Goal: reduce the Javascript reduce the Javascript reduce the Javascript reduce the Javascript forforforfor validationvalidationvalidationvalidationand format managementand format managementand format managementand format managementand format managementand format managementand format managementand format management
Example:
Form Input Types
<input type="search"> for search boxes<input type="number"> for spinboxes
for sliders<input type="range"> for sliders<input type="color"> for color pickers<input type="tel"> for telephone numbers<input type="url"> for web addresses<input type="email"> for email addresses<input type="date"> for calendar date pickers<input type="month"> for months<input type="month"> for months<input type="week"> for weeks<input type="time"> for timestamps<input type="datetime"> for precise timestamps<input type="datetime-local"> for local dates and times
Form Input Types
Form input types degradedegradedegradedegrade gracefullygracefullygracefullygracefully
� Unknown input types are treated as text-type� Unknown input types are treated as text-type
http://bit.ly/I65jai
Form Field Attributes
AutofocusAutofocusAutofocusAutofocus– Support for placing the focus on a specific form– Support for placing the focus on a specific formelement
<input type="text“ autofocus>
PlaceholderPlaceholderPlaceholderPlaceholderPlaceholderPlaceholderPlaceholderPlaceholder– Support for placing placeholder text inside a formfield<input type="text“ placeholder=“your name”>
RequiredRequiredRequiredRequired– Method of setting required fields required fields required fields required fields and field types without requiring JavaScriptrequiring JavaScript
Your Name: <input type="text" name="name" required>
PatternPatternPatternPattern– Validate form field data to match the specified regular expression patternexpression pattern
<input type="text" pattern=“[1-9]+”>
CurrentlyCurrentlyCurrentlyCurrently theytheytheythey are are are are supportedsupportedsupportedsupported bybybyby fewfewfewfew mobile mobile mobile mobile browsersbrowsersbrowsersbrowsers
New form elements
<datalist> a list of pre-defined options for input controls
<keygen> a key-pair generator field (for forms)When the form is submitted, two keys are generated, one private and one publicThe private key is stored locally, and the public key is sent to the server
<output> the result of a calculationa label that can be filled by a Javascript function
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers
Audio
<audio> : a standard way to embed an audio file on a web pagea web page
<audio controls>
<source src="song.ogg" type="audio/ogg" />
<source src="song.mp3" type="audio/mpeg" />
Not Supported
</audio></audio>
Multiple sources� the browser will use the first recognized format
Audio Javascript API
HTML5 provides a set of Javascript Javascript Javascript Javascript APIsAPIsAPIsAPIs forinteracting with an audio elementinteracting with an audio element
For example:
play() pause() load() currentTime
ended volume…
� http://www.w3.org/wiki/HTML/Elements/audio
Video
<video> : a standard way to embed a video file on a web pageweb page
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4" />
<source src="movie.ogg" type="video/ogg" />
Not Supported
</video></video>
Multiple sources� the browser will use the first recognized format
Video Javascript API
HTML5 provides a set of Javascript Javascript Javascript Javascript APIsAPIsAPIsAPIs forinteracting with a video elementinteracting with a video element
For example:
play() pause() load() currentTime
ended volume…
� http://www.w3.org/wiki/HTML/Elements/video
A note on YouTube videos
<video> works only if you have a direct link to the MP4 file of the YouTube videoMP4 file of the YouTube video
If you have just a link to the YouTube page of yourvideo, simply embed it in your page
<iframe width="560" height="315" <iframe width="560" height="315"
src="http://www.youtube.com/embed/Wp20Sc8qPeo"
frameborder="0" allowfullscreen></iframe>
A note on YouTube videos
These are the PhoneGap options you have to set
MediaPlaybackRequiresUserAction: NO
AllowInlineMediaPlayback: YES
OpenAllWhitelistURLsInWebView: YES
ExternalHosts
*.youtube.com
*.ytimg.com*.ytimg.com
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers
Offline Data
LocalStorageLocalStorageLocalStorageLocalStoragestores data in key/value pairsstores data in key/value pairsit is tied to a specific domain/apppersists across browser sessions
SessionStorageSessionStorageSessionStorageSessionStorageSessionStorageSessionStorageSessionStorageSessionStoragestores data in key/value pairsit is tied to a specific domain/appdata is erased when a browser session ends
Offline Data
WebSQLWebSQLWebSQLWebSQL DatabaseDatabaseDatabaseDatabaserelational DBrelational DBsupport for tables creation, insert, update, …transactionaltied to a specific domain/apppersists across browser sessions
Its evolution is called IndexedDBIndexedDBIndexedDBIndexedDB, but it is actuallynot supported by most mobile browsers
Mobile browsers compatibility matrix
We will have a dedicated lecture tooffline data storage on mobile devices
Application Cache
web applications can be cached, and accessible without an internet connectionwithout an internet connection
<!DOCTYPE HTML>
<html manifest=“home.appcache“>
<body>
contentscontents
</body>
</html>
Application Cache
Every page with the manifest attribute specified will be cachedbe cached
If the manifest attribute is not specified, the page will not be cached (unless the page is specified directly in the manifest file)
App cache is supported by all browsers, except IE
The Manifest File
The manifest file has three sections:
• CACHE MANIFESTCACHE MANIFESTCACHE MANIFESTCACHE MANIFEST– Files listed under this header will be cached after they will be cached after they will be cached after they will be cached after they
are downloaded for the first timeare downloaded for the first timeare downloaded for the first timeare downloaded for the first time
• NETWORKNETWORKNETWORKNETWORK– Files listed under this header require a connection to the server, and will never be cachedwill never be cachedwill never be cachedwill never be cached
– Files listed under this header require a connection to the server, and will never be cachedwill never be cachedwill never be cachedwill never be cached
• FALLBACKFALLBACKFALLBACKFALLBACK– Files listed under this header specifies fallback pages if a if a if a if a
page is inaccessiblepage is inaccessiblepage is inaccessiblepage is inaccessible
Manifest File - Example
CACHE MANIFEST
# 2012-02-21 v1.0.0# 2012-02-21 v1.0.0
/theme.css
/logo.gif
/main.js
NETWORK:
login.asp
FALLBACK: The first URI is the FALLBACK:
/html5/ /offline.html
http://bit.ly/I6gmAc
The first URI is the resource, the second is
the fallback.
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers
Geolocalization
Gets Latitude and Longitude from the user’s browser
There is also a watchPosition method wich calls a JS function every time the user moves
We will have a dedicatedWe will have a dedicatedlecture to geolocalization on
mobile devices
Example
function getLocation() {function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log(‘no geolocalization’);
}
}
function showPosition(position) {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
}
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers• Microdata
WebSockets
Bidirectional, fullBidirectional, fullBidirectional, fullBidirectional, full----duplex communicationduplex communicationduplex communicationduplex communication between devices and serverdevices and server
Specifically suited for
chat, videogames, drawings sharing, real-time info
Requires a Web Socket Server to handle the protocolRequires a Web Socket Server to handle the protocol
We will have a dedicatedlecture to WebSockets on
mobile devices
WebSockets - Overview
1.1.1.1. Client notifies Client notifies Client notifies Client notifies websocketwebsocketwebsocketwebsocket server server server server (EventMachine) of an event, giving ids of recipientsevent, giving ids of recipients
2. The serverserverserverserver notifies all the active clients notifies all the active clients notifies all the active clients notifies all the active clients (subscribed to that type of event)
3.3.3.3. Clients process event Clients process event Clients process event Clients process event
when given recipient Id
matches the client’s one
http://bit.ly/Ixcupi
Alternative - Polling via AJAX
+ Near real-time updates (not purely real-time)
+ easy to implement+ easy to implement
+ no new technologies needed
- they are requested from the client and cause increased network traffic
- AJAX requests generally have a small payload and relatively high amount of http headers (wasted bandwith)
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers
Server-Sent Events
It setups a persistent http connection persistent http connection persistent http connection persistent http connection which has to be setup only once
We will have a which has to be setup only once
It is unidirectionalunidirectionalunidirectionalunidirectional: : : : server � client
We will have a dedicated
lecture to SSE on mobile devices
SSEs are sent over traditional HTTPSSEs are sent over traditional HTTPSSEs are sent over traditional HTTPSSEs are sent over traditional HTTP� it can be easily implemented with standard server-side technologies (eg PHP)
devices
Server-Sent Events
Specifically suited for:
• financial info• financial info
• twitters updates
• friends' status updates
• news
If you need to send data to a server, you can still use XMLHttpRequests via Javascript
SSE- Overview
1. Client sends a request sends a request sends a request sends a request to the server via HTTP
2. The server creates a process, which fetches latest state in 2. The server creates a process, which fetches latest state in the DB and responds backresponds backresponds backresponds back
3. Client gets server responsegets server responsegets server responsegets server response
4. In 3 seconds client automatically sends next request sends next request sends next request sends next request to the server
http://bit.ly/Ixcupi
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers
Canvas & SVG
Canvas & SVG allow you to create graphics inside the browserinside the browser
We will have a dedicated lecture todedicated lecture to
canvas & SVG on mobile devices
http://bit.ly/Ie4HKu
Canvas & SVG
CanvasCanvasCanvasCanvas
draws 2D graphics, on the flydraws 2D graphics, on the fly
you use Javascript to draw on the canvas
rendered pixel by pixel
SVGSVGSVGSVGSVGSVGSVGSVG
describes 2D graphics in XML
every element is available within the SVG DOM
JavaScript event handlers for an element
Roadmap
• IntroIntroIntroIntro• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• New New New New StructuralStructuralStructuralStructural TagsTagsTagsTags and and and and AttributesAttributesAttributesAttributes• FormsFormsFormsForms• Audio & VideoAudio & VideoAudio & VideoAudio & Video• Offline Data• Geolocalization• Web Sockets• Server-Sent Events• Canvas & SVG• Web Web Web Web WorkersWorkersWorkersWorkers
Web Workers
Javascript is a singlesinglesinglesingle----threadedthreadedthreadedthreaded languagelanguagelanguagelanguage
� If a tasks take a lot of time, users have to wait� If a tasks take a lot of time, users have to wait
Web Workers provide background processing background processing background processing background processing capabilities to web applications
They typically run on separate threads run on separate threads run on separate threads run on separate threads
� apps can take advantage of multicore CPUs
Web Workers
Web Workers can be used to:
• prefetchprefetchprefetchprefetch data from the Web
• perform other aheadaheadaheadahead----ofofofof----time operations time operations time operations time operations to provide a much more lively UI.
Web Workers are precious on mobile Web applications Web Workers are precious on mobile Web applications because they usually need to load data over a potentially slow networkslow networkslow networkslow network
Web Workers
Any JS file can be launched as a worker
Example of Web Worker declaration:
var worker = new Worker(“worker.js”);
In order to be independent from other workers, eachworker script cannot access the DOMworker script cannot access the DOM
Web Workers
The main JS script can communicate with workers via postMessage() calls:postMessage() calls:
$(‘#button’).click(function(event) {
$(‘#output’).html(“starting”);
worker.postMessage(“start”);
});});
worker.onmessage = function(event) {
$(‘#output’).html(event.data);
}
Web Workers
The web worker script can post back messages to the main script:main script:
onmessage = function(event) {
if(event.data === “start”) {
var result;
// do something with result// do something with result
postMessage(result);
}
}