html5 comprehensive guide
DESCRIPTION
Quick-guide and reference material for HTML5 developers.TRANSCRIPT
HTML 5
What is HTML5?
“Specification that defines the 5th major revision of the core language of the
World Wide Web: HTML.”
World Wide Web Consortium
What is HTML5?
+ +
What is HTML5?
New Cool
Who’s in charge?
WHATWGW3C
HTML WG
Browser Vendors
Who’s in charge?
Ian HicksonEditor of HTML5 specification
Standardisation
Editor`s DraftFirst Public
Working DraftLast Call
Candidate Recommendation
Recommendation
State of HTML5
“So we opened a mailing list called the WHATWG to continue work
on Web Forms 2.0 in public, and later that year started a new draft called Web Applications 1.0 into which we put many features aimed at writing Web apps, including a new version of HTML that we
jokingly called HTML5…”
2004
Ian Hickson
State of HTML5
State of HTML5Early expectations
2012 – W3C Candidate Recommendation
W3C Recommendation
2020?
State of HTML5Reality
2012 – W3C Candidate Recommendation
W3C Recommendation
2014
State of HTML5Old browsers (Q1 2013)
More on: www.html5test.com
~ 33%IE 6-8
FF 3-3.6
OP 9x
State of HTML5Mobile Platforms
Various degree of support in mobile operating systems.
iOS Android Window Phone BlackBerry
State of HTML5
jQuery 2.0Drops support of legacy browsers
State of HTML5
“JQuery 2.0 now has more patches and shims for Chrome, Safari, and Firefox than
for Internet Explorer.”
Dave MethvinPresident, jQuery Foundation
State of HTML5
Web
Native
Classic Web
Desktop (PC)
RIA
“HTML5”Web
State of HTML5Already moved to HTML5
State of HTML5“When I`m introspective about last few years I think the biggest mistake we made as a company was betting too much on HTML5 as opposed to native… because it just wasn`t there. … We burned two years. It`s really painful.”
Mark ZuckerbergSEO of Facebook, September 2012
Goals of HTML5
Native Multimedia
Programmatic Context
Enhanced Web Semantics
“Plug-in free” Development
Goals of HTML5Adobe Flash
What is wrong with Adobe Flash?Lot of security vulnerabilities Low performance on older machinesDisallowed on mobile devicesRequires user to install separate plug-in
Goals of HTML5Silverlight
What is wrong with Silverlight?Tied to WindowsRequires user to install separate plug-inHistorical dislike of Microsoft
State of HTML5Be pragmatic
StabilityUse what works
today
GranularityUse what you need
RationalityWeb Standards not
always fit
State of HTML5“And it`s not that HTML5 is bad. I`m actually, on long-term, really excited about it. One of the things that`s interesting is we actually have more people on a daily basis using mobile Web Facebook than we have using our iOS and Android apps combined. So mobile Web is a big thing for us.”
Mark ZuckerbergSEO of Facebook, September 2012
HTML5How to take advantage of HTML5?
You already, DO!
How to enable HTML5 standards mode in browsers?
<!DOCTYPE html>Place this on top of your document. No DTD!
HTML5Tools
Visual Studio 2012 with Web
Essentials.
For .NET Developers
Expression Web
For non .NET Developers
Adobe Dreamweaver
Aptana Studio
JetBrains WebStorm
HTML5Storage API`s
Web SQL IndexedDBWeb Storage
Local Storage Session Storage
Web StorageLocal Storage
Persistent store for up to 5 MiB of data on users local machine (10 MiB for IE)
Essential details
Never transferred to server side (no-cookies)
Accessible from JavaScript
Store for Key-Value pairs of strings
Important notes
Objects should be stringifyed prior to saving to localStorage
It is allowed for browser to clear localStorage without user permission
Go to full specification
Web StorageSession Storage
Non-Persistent store for up to 5 MiB of data on users local machine (10 MiB for IE)
Essential details
Go to full specification
Data accessible only during current session (browser tabs)
Shares API with localStorage
Web StorageLocal Storage & Session Storage
setItem(key, value) - to set something to the browsers storage
API
Go to full specification
getItem(key) – to get value from storage
removeItem(key) – to remove item from storage
clear() – to clear storage
Web SQLEssentials
What`s is Web SQL?
Go to full specification
Web SQL Database is a web page API for storing data in databases that can be queried using a variant of SQL
Full power of relational database on client side
Support for transactions
Specification based on SQLite
Synchronous and asynchronous API
Web SQL
What`s the state of Web SQL?
Go to full specification
Deprecated! Working Group does not intend to maintain it further.
What`s wrong with Web SQL?All interested implementers have used the same SQL backend (SQLite), but W3C need multiple independent implementations to proceed along a standardization path.
Essentials
Web SQLGo to full
specification
openDatabase – opens or creates databaseAPI
transaction – creates transaction
executeSql – used for executing SQL read and write statements
IndexedDBEssentials
What`s is IndexedDB?
Go to full specification
IndexedDB is an API for client-side storage of significant amounts of structured data
It`s an object store, but it`s not a relational database.
Support for transactions
Support for indexes
Synchronous and asynchronous API
IndexedDBEssentials
Specific terms of IndexedDB
Go to full specification
Database comprises one or more object stores which hold the data stored in the database
Object Store is the primary storage mechanism for storing data in a database
Transaction is used to interact with the data in a database
Request represents one read or write operation
HTML5Native multimedia
Multimedia
Video Audio
Native MultimediaEssentials
Abstract MediaElement
Audio & Video has common API
First class citizen of DOM
Application Programming Interface
Native MultimediaProgrammatic Context
Go to full specification
Events
Network-related
Buffering level
Playback control and feature detection
Native MultimediaEvents
Go to full specification
Loadstart Progress Suspend Abort
Error Emptied Stalled
Network-related
loadedmetadata loadeddata waiting
playing canplay canplaythrough
Buffering level
Native MultimediaJavaScript & CSS
Go to full specification
First-class DOM citizen and can be styles with CSS3
Exposes properties and functions to JavaScript
Properties Functions
playbackRate
volume
muted
networkState
readyState
currentTime play
pause
load
Native MultimediaFormat Support
Go to full specification
“…regarding codecs for <video> and <audio> in HTML5, Ihave reluctantly come to the conclusion that there is nosuitable codec that all vendors are willing to implementand ship.”
Ian Hickson
AudioEssentials
Built in tag <audio> for embedding audio player
Natively support – require no plug-ins
Out of the box user interface
API for controlling audio playback
Go to full specification
AudioEssentials
Go to full specification
Attributes of <audio> tag
Src - media content source
Preload - attribute is intended to provide a hint to the user agent about what the author thinks will lead to the best user experience.
None – do not preloadMetadata – preload metadata onlyAuto – let browser decide
Controls – specifies whether built-in controls visible or not
Loop - indicates that the media element should to seek back to the start
Crossorigin - indicates that audio file is being served from different origin
AudioEssentials
Go to full specification
Tools of the Devil
Loop - indicates that the media element should to seek back to the start
Autoplay - indicates that the media element should automatically start playback once its fully loaded
AudioLook & Feel
Go to full specification
How does it looks like? What the markup is?
<audio controls="controls">
<source src="song.ogg" type="audio/ogg" />
<source src="song.mp3" type="audio/mpeg" />
Your browser does not support the audio element.
</audio>
AudioProgrammatic Context
Go to full specification
play - to play audio
API
pause – to pause audio
canPlayType(type) – determines whether type supported by user agent
buffered – attribute that specifies the start and end time of the buffered part of the file
AudioFormat Support
Go to full specification
MP3 WebM OGG AAC
VideoEssentials
Built in tag <video> for embedding video player
Natively support – require no plug-ins
Out of the box user interface
API for controlling video playback
Go to full specification
VideoVideo formats
Go to full specification
MPEG4
+
WebM
+
OGG
+
VideoEssentials
Go to full specification
Attributes of <video> tag
Src - media content source
Preload - attribute is intended to provide a hint to the user agent about what the author thinks will lead to the best user experience.
None – do not preloadMetadata – preload metadata onlyAuto – let browser decide
Controls – specifies whether standard controls visible or not
Poster – image to show while no video data is available
VideoLook & Feel
Go to full specification
How does it looks like? What the markup is?
<video width="320" height="240" controls="controls">
<source src="movie.mp4" type="video/mp4" />
<source src="movie.ogg" type="video/ogg" />
Your browser does not support the video tag.
</video>
VideoIssues
Go to full specification
Fullscreen playing
Live Streaming
Patchy browser support
CanvasEssentials
Go to full specification
HTML5 element that allows for dynamic, scriptable rendering of 2D shapes and bitmaps
Immediate mode rendering
Rich API: 45 methods, 21 attributes
Future plans for 3D rendering
CanvasGo to full
specification
API
Application Programming Interface
State
Transformations
Compositing
Color & Styles
Line caps/joins
Shadows
Rectangles
Path API
Text
Pixel manipulation
Focus management
Drawing images
CanvasHistory
Go to full specification
Developed as platform for OSX Dashboard Widgets
in 2004
CanvasUse cases
Go to full specification
Data visualization
CanvasUse cases
Go to full specification
Animated graphics
CanvasUse cases
Go to full specification
Web Applications
CanvasUse cases
Go to full specification
Games
CanvasMarkup
Go to full specification
What the markup is?
<canvas width=‘800’ height=‘600’>Your browser doesn`t support canvas.
</canvas>
CanvasCoordinate System
Go to full specification
(0, 0) X
Y
CanvasRendering Context
Go to full specification
2D Rendering Context
Everything is drawn onto 2D rendering context that is tied to Canvas instance
CanvasRendering Context
Go to full specification
Context instance can be preserved and passed around the app
How to get context?
var canvas = document.getElementById(‘canvas’)var context = canvas.getContext(‘2d’)
CanvasDrawing Model
Go to full specification
How to change color?
var canvas = document.getElementById(‘canvas’)var context = canvas.getContext(‘2d’)
context.fillStyle = ‘black’;context.strokeStyle = ‘white’;
CanvasDrawing Model
Go to full specification
fillRect - draws a rectangle using current fill style
Simple shapes
strokeRect – draws the outline of a rectangle using the current stroke style
clearRect – clears all pixels within the given rectangle
CanvasDrawing Model
Go to full specification
Complex shapes
A new patch should be created for each complex shape
Paths are a list of subpath
Subpaths are one or more points connected by straight or curved lines
Rendering context has reference to current active path
CanvasDrawing Model
Go to full specification
Complex shapes
beginPath – resets the current path
closePath – closes the current subpath and starts a new one
fill – fills the subpaths with the current fill style
stroke – outlines the subpaths with the current stroke style
CanvasDrawing Model
Go to full specification
Complex shapes
lineTo – draws a straight line from the previous point
rect – adds a new closed rectangular subpath
arc – adds a subpath along the circumference of the described circle, withing the angles defined
arcTo – adds a subpath connecting two points by an arc of the defined radius
CanvasDrawing Model
Go to full specification
Transformations
Affects shapes and paths drawn after the transformation
Shorthand methods for translation, scaling, rotation
Transformation matrices are allowed
CanvasDrawing Model
Go to full specification
Transformations
translate – moves coordinate system by specified offset
rotate – rotates coordinate system by specified angle
scale – scales coordinate system by specified factor
transform – multiplies current transformation matrix with specified one
setTransform – sets transformation matrix directly
CanvasDrawing Model
Go to full specification
ctx.shadowOffsetX = 10;ctx.shadowOffsetY = 10;ctx.shadowBlur = 10;ctx.shadowColor = "rgba(0, 0, 0, 1)";ctx.fillText(“Winning!”, 10, 25);
// All future operations will also have a shadowctx.strokeRect(0, 0, 115, 40);
All Canvas attributes are global – they effect all operations drawn next.
CanvasDrawing Model
Go to full specification
The current values of the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline.
You can save and restore:
The current transformation matrix.
The current clipping region.
CanvasState Management
Go to full specification
ctx.save();ctx.shadowOffsetX = 10;ctx.shadowOffsetY = 10;ctx.shadowBlur = 10;ctx.shadowColor = "rgba(0, 0, 0, 1)";ctx.fillText(“Winning!”, 10, 25);ctx.restore();
// All future operations will NOT have a shadowctx.strokeRect(0, 0, 115, 40);
Use save() and restore() to scope the attribute
CanvasComposition
Go to full specification
Compositing it the control of transparency and layering of objects
Controlled by globalAlpha and globalCompositeOperationattributes
CanvasComposition
Go to full specification
CanvasDrawing Model
Go to full specification
Firefox, Opera and Internet Explorer follow the drawing model as described in the spec.
Safari and Chrome have a slightly different drawing model behavior.
DO: Check if you’re composition is impacted by this interoperability issue.
CanvasPerformance
Go to full specification
Not all operations were made equal. Some are more expensive than others
Shadows, clipping and composition operations are more expensive as they require an additional intermediate.
DON’T: Create thousands of small objects with clipping, shadows or compositions effects.
CanvasSecurity Model
Go to full specification
Canvas allows reading and writing pixels to the screen
You can also save the Canvas to a file via toDataURL()
Canvas PNG File
Canvas also allows drawing cross-domain images/videos
However, it has built-in security protection against third-parties saving cross-domain pixels
CanvasSecurity Model
Go to full specification
Canvas
PNG File
CanvasSecurity Model
Go to full specification
Canvas has a concept of origin-clean flag.
origin-clean is set false if a cross-domain IMG or VIDEO is used.
A SECURITY_ERR exception is raised, if one tries to save the Canvas pixels if the Canvas origin-clean is false:
toDataURL()
getImageData()
Animation Frame APIEssentials
Go to full specification
API for getting precise animation updates
User Agent schedules updates in sync with internal redraw routines
Automatic management of update time and low-power mode
Animation Frame APIGo to full
specification
requestAnimationFrame – requests repaint callback to be scheduled API
cancelAnimationFrame – cancels repaint callback request
HTML5Media Capture
User Media API
HTML Media Capture
HTML Media CaptureEssentials
Native media capture mechanism
Extends file input
Allows to capture audio, video and photo
HTML Media CaptureMarkup
What the markup is?
<input type="file" accept="image/*" capture="camera" /> <input type="file" accept="audio/*" capture="microphone" /> <input type="file" accept="video/*" capture="camcorder" />
Media format controlled by accept attribute
Media type controlled by capture attribute
User Media APIEssentials
API that allows to capture media streams
Designed to interoperate with related specs
Allows to capture audio, video and photo
User Media APIEssentials
High level abstraction for streaming data
Can be passed around to different APIs
Contains audio and video tracks
Media Stream
Media Stream Track
High level abstraction for media stream source
User Media APIMedia Stream
User Media APIProgrammatic Context
Go to full specification
getUserMedia - to start capturing media stream
API
HTML5Audio Processing
Web Audio API
Audio Data API
JavaScript DSP
JavaScript DSPEssentials
Byte-level manipulations with encoded audio data
Getting audio data via XMLHttpRequest or File API
Requires knowledge of DSP and audio formats encoding
Extension: Firefox allows access to PCM data
Web Audio APIWhy?
<audio> hides the steps of loading, decoding and playing
No standard way to access raw PCM data
No fine-grained timing
No concept of position and direction of sources and listeners
Hard to analyze and visualize data on the fly
Web Audio APIEssentials
High-level API for processing and synthesizing audio
Gives fine grained control over audio processing and playback
Web Audio API
Real-time processing and synthesizing audio
Capabilities
An audio pipeline and routing system for effects and filters
Web Audio API
Access to raw PCM data
Capabilities
Web Audio API
Precise scheduling of audio playback
Capabilities
Web Audio APIAudio Context
Abstract representation of audio signal graph and connections between AudioNodes
Web Audio APIAudio Context
API
destination – audio node that represents actual hardware
sampleRate – the sample rate at which Audio Context handles audio
currentTime – time in seconds tied to hardware clock
listener – an audio listener that is used for 3D spatialization
Web Audio APIAudio Node
Build block of audio graph
Audio node represents
Source
Destination
Intermediate processing module
Set of predefined Audio Nodes as well as ScriptProcessorNode
Web Audio APIAudio Node
AudioDestinationNode AudioBufferSourceNode MediaElementAudioSourceNode
MediaStreamAudioSourceNode MediaStreamAudioDestinationNode ScriptProcessorNode Audio Effect Nodes
Web Audio APIAudio Buffer
Represents in-memory audio asset
Contains IEEE 32-bit linear PCM with a nominal range of -1 -> +1
Contains one or more channels
Typically expected that length of PCM data would be less than a minute
Long audio tracks can be served via MediaElementAudioSourceNode
HTML53D
WebGL
Image-based 3D
CSS3 3D Transforms
Software rendering on Canvas
HTML5Image-based 3D
Set of prerendered images
High degree of browser support
Terrific amount of data to load
No client side customizations
Image-based 3DImage-based 3D
Fast image switches may cause flickering
Rendering to Canvas may give significant performance boost
HTML5Software Rendering
Rendering and computations are made on CPU
Manual manipulations with Pixel and Vertex data
Canvas as rasterization surface
Software RenderingPerformance
Software rendering is inherently slow
Good enough for simple scenes
Mobile devices are still a concern
HTML5CSS3 Transforms
Display-time transformations of any HTML contenttransforms do not affect layout
3D Transformstranslate, scale, rotate, skew in X, Y & Zperspective
CSS3 TransformsEssentials
Rendering and computations are made on GPU
Applies to any DOM element
Declarative and programmatic control
HTML5CSS Custom Shaders
User supplied program for GPU programming
Executes in parallel
Source of awesome visual effects
Programmed in GLSL
CSS Custom ShadersShowcase
CSS Custom ShadersRendering Pipeline
CSS Custom ShadersTypes
Fragment Shader
Vertex Shader
CSS Custom ShadersFragment Shader
GPU program for pixel color manipulation
The result is a pixel color
Executes in parallel on GPU infrastructure
Currently there is no way to set via gl_FragColor
Fragment ShaderSample
precision mediump float;
void main() {
float r = 1.0;float g = 1.0;float b = 1.0;float a = 1.0;
css_ColorMatrix = mat4( r, 0.0, 0.0, 0.0,0.0, g, 0.0, 0.0,0.0, 0.0, b, 0.0,0.0, 0.0, 0.0, a );
}
CSS Custom ShadersVertex Shader
Responsible for mesh deformations
The result is a vertex position
Executes in parallel on GPU infrastructure
Vertex ShaderSample
precision mediump float;
attribute vec4 a_position;uniform mat4 u_projectionMatrix;
void main() {gl_Position = u_projectionMatrix * a_position;
}
Projection matrix is supplied by a web browser.
a_position stores vertex position
CSS Custom ShadersSyntax
#myelement {filter: custom( vertex-shader
[ fragment-shader][,vertex-mesh][,params]);
}
How to apply shader?
CSS Custom ShadersVertex Creation
#myelement {filter: custom( vertex-shader
[ fragment-shader],4 5[,params]);
}
How to apply shader?
CSS Custom ShadersUniforms
#myelement {filter: custom( vertex-shader
[ fragment-shader],4 5, amount 0);
}
CSS
precision mediump float;
uniform float amount;
void main(){}
Fragment Shader
WebGLEssentials
It is a software library that extends the capability of the JavaScript to allow it to generate 3D graphics
Uses canvas as rendering surface
Based on OpenGL ES 2.0
WebGLStandard
WebGLSupport
“We believe that WebGL will likely become an ongoing source of hard-to-fix vulnerabilities. In its current form, WebGL is not a technology Microsoft can endorse from a security perspective.”
MicrosoftJune 16, 2011
WebGLSupport
“I agree with Microsoft’s assessment that WebGL is a severe security risk. The gfx driver culture is not the culture of security.”
John CarmackCo-founder of Id Software, June 2011
WebGLArchitecture
Typed ArraysEssentials
Efficient way to pass data into API`s
C-like arrays
Memory can be passed directly to native API`s
Typed ArraysArray Buffer
Abstract representation of binary data
Serves as a data-source for typed arrays
Integrated with other HTML API`s
Typed ArraysArray Buffer View
Int8Array Uint8Array Int16Array Uint16Array Int32Array
Uint32Array Float32Array Float64Array Uint8ClampedArray
Typed ArraysData View
Simplifies manipulations with heterogeneous types
Supports big and little endian
Be careful with alignment
Typed ArraysInteroperability
WebGL Canvas 2D File APIWeb
Sockets
XHR2Media Source
Transferable objects
Same Origin PolicyGo to full
specification
Security
Browser-level Firewall
Prohibits sending security sensitive information to foreign locations
Prohibits read of resources from foreign origin
Primary security barrier against XSS and Cookie stealing attacks
What is same origin policy?
Same Origin PolicyGo to full
specification
Security
What origins are foreign?http://www.example.com
Same protocol and host but different porthttp://www.example.com:81
Different protocolhttps://www.example.com
Different hosthttp://en.example.com
Web MessagingEssentials
Go to full specification
Mechanism for cross-document communication
Support for cross-origin communication
API for exchanging plain text messages and structured data
What is Web Messaging?
Web MessagingCommunication
Go to full specification
Window object
Message Channel
Web MessagingEssentials
Go to full specification
The end of iframe hacks!
Web MessagingAPI
Go to full specification
postMessage() – to post message to window
Message event – event raised when new message arrived
Web WorkersGo to full
specification
JavaScript is inherently single threaded
Asynchronous through single message loop
No concurrency, no thread synchronization
Motivation
Web WorkersIssue
Go to full specification
“[JavaScript] that executes in whole seconds is probably doing something wrong...”
Brendan EichCreator of JavaScript, Mozilla Foundation
Web WorkersEffect
Go to full specification
Web WorkersOld-school solutions
Go to full specification
Partition work with
timers
Offload work to server
Web WorkersEssentials
Go to full specification
JavaScript native ‘threading’ mechanism
True parallelism
Designed to be long-lived
High startup cost performance and memory cost
What are Web Workers?
Web WorkersEssentials
Go to full specification
Loaded from separate file or Blob
Communication with parent script through messages and events
Can be terminated from inside and outside
Due to their multi-threaded behavior, web workers only has access to a subset of DOM and BOM features
How it works?
Web WorkersScope
Go to full specification
The navigator object
The location object (read-only)
XMLHttpRequest
setTimeout(), setInterval()
The application cache
Importing external scripts using the importScripts() method
Spawning other Web Workers
Features Available to Workers
Web WorkersScope
Go to full specification
DOM and BOM
window object
document object
parent object
Features Unavailable to Workers
Web WorkersTypes
Go to full specification
Dedicated Shared
Web WorkersTransferable Objects
Go to full specification
Structured data can be passed without copying
Huge performance win
Supported structured objects:
ArrayBufferMessagePort
CanvasProxy
Web WorkersTransferable Objects
Go to full specification
HTML5Go to full
specification
Real-time Communications
HTTP protocol has one request – one resource semantics
No built-in mechanism for Push Notifications
Semi-duplex communications
Overhead of HTTP headers
Real-timeGo to full
specification
Use cases
Live feeds
Real-timeGo to full
specification
Use cases
Multiplayer games
Real-timeGo to full
specification
Use cases
Live sync applications
Real-timeGo to full
specification
Workarounds
Polling Comet
Real-timeGo to full
specification
Polling
Periodic HTTP requests
High server workload
High latency
High degree of support across different browsers
PollingGo to full
specification
Interaction diagram
PollingGo to full
specification
Network throughput
Real-timeGo to full
specification
Comet
Periodic long-lived HTTP requests
Reduced traffic
Reduced server workload
Overhead of HTTP headers
Possible difficulties with proxies and load balancers
CometGo to full
specification
Interaction diagram
CometGo to full
specification
Types
Long polling
HTTP Streaming
Web SocketsGo to full
specification
Essentials
Full-duplex socket connection
Web Socket protocol v13 (RFC 6455) instead of HTTP
Uses HTTP for connection establishment
Low-latency client-server communication technology
Web SocketsGo to full
specification
Connection Establishment
Runs via port 80/443 to simplify firewalls traversal
Pseudo schemes: ws, wss
Connection established by “upgrading” from HTTP to WebSocketprotocol
Web SocketsGo to full
specification
Opening handshake
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Client sends GET or CONNECT request to Web Socket endpoint
Upgrade header indicates willing to upgrade connection from HTTP to WebSocket
Web SocketsGo to full
specification
Opening handshake
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Server responds with 101 status code and connection upgrade header
From now on Web Socket protocol will be used instead of HTTP
Web SocketsGo to full
specification
API
var connection = new WebSocket('ws://html5rocks.websocket.org/echo');
Connection
Communication
// When the connection is open, send some data to the
server
connection.onopen = function () {
// Send the message 'Ping' to the server
connection.send('Ping');
};
// Log errors
connection.onerror = function (error) {
// Log messages from the server
console.log('WebSocket Error ' + error);
};
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
Server-sent EventsGo to full
specification
Essentials
Support for auto reconnect
Support for event ids
Requires Content-Type: text/event-stream
Browser built-in long polling mechanism
Server-sent EventsGo to full
specification
Essentials
data: This is the first message.
data: This is the second message, it
data: has two lines.
data: This is the third message.
Response
event: add
data: 73857293
event: remove
data: 2153
event: add
data: 113411
Response with named Events
XHR Level 2Go to full
specification
Essentials
What is XHR?
API for sending HTTP and HTTPS requests directly to Web Server
Supports plain text and structured response formats
Interaction without page refresh
Basement of AJAX
XHR Level 2Go to full
specification
Interaction Model
AJAX
JavaScript
Document Object Model
XHR
Asynchronous Web calls
DHTMLmanipulations
XHR Level 2Go to full
specification
Security
Strong security concerns
Same origin policyCross-origin resource
sharing policy
XHR Level 2Go to full
specification
Security
Cross-origin communication scenarios
JSONP CORSBlind
Proxies
Web Messaging
Iframehacks
HTTP forgery
XHR Level 2Go to full
specification
Security
Way for a web server to allow its resources to be accessed by a web page from a different domain
Requires server & client side support
Server side decides which origins are allowed
HTTP header based negotiation
What is cross-origin resource sharing?
XHR Level 2Go to full
specification
Security
XHR Level 2Go to full
specification
Security
Request
GET http://photos.contoso.com/albums HTTP/1.1Origin: http://www.contoso.com
Origin header specifies that this is CORS aware request.
Response
HTTP/1.1 200 OKAccess-Control-Allow-Origin: http://www.contoso.com
Server respond with special header that allows browser to consume such response
XHR Level 2Go to full
specification
Security
Request
OPTIONS http://photos.contoso.com/albums HTTP/1.1Origin: http://www.contoso.comAccess-Control-Request-Method: PUT
In case of non-safe methods web browser should send preflight request prior to sending actual request
Response
HTTP/1.1 200 OKAccess-Control-Allow-Origin: http://www.contoso.comAccess-Control-Allow-Methods: PUT
Server respond with special header that allows browser to make actual request
XHR Level 2Go to full
specification
Features
Cross-origin requests
Uploading progress events
Uploading downloading
structured data
XHR Level 2Go to full
specification
Features
Structured dataAllows to get resources as structured object
Allows to post data as structured object
Controlled via responseType property
New response property to consume resource in structured format
XHR Level 2Go to full
specification
Features
Structured formats (upload)
ArrayBuffer – generic fixed-length binary data buffer
FormData – object based representation of form fields
Blob – url accessible container for binary data
Document
DOMString – plain text response
XHR Level 2Go to full
specification
Features
Structured formats (download)
arraybuffer – generic fixed-length binary data buffer
blob – url accessible container for binary data
document
text – plain text response
json – json string converted into object
XHR Level 2Go to full
specification
Features
Structured data var xhr = new XMLHttpRequest(); xhr.open('GET', '/path/to/image.png', true); xhr.responseType = 'arraybuffer';
xhr.onload = function(e) { var uInt8Array = new Uint8Array(this.response); var byte3 = uInt8Array[4]; // byte at offset 4 ...
};
xhr.send();
GET example
GeolocationEssentials
Go to full specification
Mechanism for determining user geographic coordinates
Available on desktop and mobile devices
Uses GPS, A-GPS, Wi-Fi hotspots or IP address range to determine current coordinates
Easy to use JavaScript API
Strong security concerns
What is Geolocation?
GeolocationAPI
Go to full specification
Main object – navigator.geolocation
getCurrentPosition – gets current position & speed (if possible)
watchPosition – track position changes
clearWatch – stop tracking position changes
Device OrientationEssentials
Mechanism for determining Euler`s angles (rotation around X,Y, Z)
Supported on broad variety of mobile devices
What is device orientation?
The deviceorientation event with orientation data passed along
The devicemotion event with orientation and acceleration data passed along
Application CacheEssentials
Go to full specification
Software storage feature which provides the ability to access a web application even without a network
Controlled by a plain text file called a cache manifest
Can be managed by JavaScript API
What is Web Application Cache?
Application CacheManifest file
Go to full specification
Contains a list of resources to be stored for use when there is no network connectivity
Defines conditions for caching
Consist of sections
CACHE – a list of explicit urls to request and store
FALLBACK - What to do when an offline user attempts to access an uncached file
NETWORK – Which resources are available only when online
Application CacheManifest file
Go to full specification
<!DOCTYPE HTML>
<html manifest="/cache.appcache">
<body> … </body>
</html>
Page markupCACHE MANIFEST
# This is a comment
CACHE:
/css/screen.css
/css/offline.css
/js/screen.js
/img/logo.png
http://example.com/css/styles.css
FALLBACK:
/ /offline.html
NETWORK:
*
Manifest file
CSS 3
Graphics FeaturesTransparency
color specification with alpha, opacity propertyRound corners
border-radiusShadows
box-shadow, text-shadowBackground gradients
linear, radialTypography
Web Open Font Format (WOFF) fonts
2D & 3D TransformsDisplay-time transformations of any HTML content
transforms do not affect layout
2D Transformstranslate, scale, rotate, skew
3D Transformstranslate, scale, rotate, skew in X, Y & Zperspective
Animations & TransitionsTransitions
smooth animation of CSS properties from old to new valuecan be used with CSS pseudo-classes such as :hover
Animationskeyframe-based definition of a set of CSS property changesallows richer animations than CSS Transitionsevent model allows complex use in combination with script
Animations & Transitions
#id_of_element { -webkit-transition: all 1s ease-in-out; -moz-transition: all 1s ease-in-out; -o-transition: all 1s ease-in-out; -ms-transition: all 1s ease-in-out; transition: all 1s ease-in-out;
}
Transition
@keyframes resize { 0% { padding: 0; } 50% {
padding: 0 20px; background-color:rgba(255,0,0,0.2);
} 100% {
padding: 0 100px; background-color:rgba(255,0,0,0.9);
} }
#box { animation-name: resize; animation-duration: 1s; animation-iteration-count: 4; animation-direction: alternate; animation-timing-function: ease-in-out; }
Animation
Markup
New Tags
Semantic Input types Multimedia Other
New Tags<article>
Specifies independent, self-contained content, could be a news-article, blog post, forum post, or other articles which can be distributed independently from the rest of the site.
<aside>For content aside from the content it is placed in. The aside content should be related to the surrounding content
<bdi>For text that should not be bound to the text-direction of its parent elements
<command> A button, or a radiobutton, or a checkbox
<details> For describing details about a document, or parts of a document
<summary> A caption, or summary, inside the details element
<figure> For grouping a section of stand-alone content, could be a video
<figcaption> The caption of the figure section
<footer>For a footer of a document or section, could include the name of the author, the date of the document, contact information, or copyright information
<header> For an introduction of a document or section, could include navigation
<hgroup>For a section of headings, using <h1> to <h6>, where the largest is the main heading of the section, and the others are sub-headings
<mark> For text that should be highlighted
<meter>For a measurement, used only if the maximum and minimum values are known
<nav> For a section of navigation
<progress> The state of a work in progress
<ruby> For ruby annotation (Chinese notes or characters)
<rt> For explanation of the ruby annotation
<rp> What to show browsers that do not support the ruby element
<section>For a section in a document. Such as chapters, headers, footers, or any other sections of the document
<time> For defining a time or a date, or both
<wbr> Word break. For defining a line-break opportunity.
Semantic Markupdiv=”header”
div=”nav”
div=”footer”
div=”article” div=”sidebar”
div
HTML4 XHTML4
Semantic Markup<header>
<nav>
<footer>
<article> <aside>
<section>
HTML5 XHTML5
Semantic Markup
Input Types13 new input types
Built-in client-side validation
Poor support in desktop browsers
See browser compatibility information
Input Types
search tel url email datetime
date month week timedatetime-
local
number range color
HTML5Feature detection
Never use navigator.userAgent browser detection hack
Never use conditional comment in Internet Explorer
Use feature detecting instead of browser detection when possible
Consider graceful fallback
Use Modernizr
Feature detectionModernizr
Modernizr is a small JavaScript Library that detects the availability of native implementations for next-generation web technologies
What is Modernizr?
Why Modernizr?
Easy to use
Powerfull feature detection library
Feature detectionModernizr
Modernizr does its “magic” by creating an element, setting a specific style instruction on that element and then immediately retrieving it
How it works?
Feature detection results available to developer via JavaScript Modernizr object and classes applied to HTML DOM element
Feature detectionModernizr
How it looks like?
/* In your CSS: */
.no-audio #music {
display: none; /* Don't show Audio options */
}
.audio #music button {
/* Style the Play and Pause buttons nicely */
}
<!-- In your HTML: -->
<div id="music">
<audio>
<source src="audio.ogg" />
<source src="audio.mp3" />
</audio>
<button id="play">Play</button>
<button id="pause">Pause</button>
</div>
LinksUseful HTML5 content
http://www.html5rocks.com
HTML5 news, demos, presentations
http://www.html5doctor.com
Lot of HTML5 tutorials, articles
http://ie.microsoft.com/testdrive/Graphics/h
ands-on-css3/
HTML5 Hands-On
THE END