HTML5 Comprehensive Guide
Upcoming SlideShare
Loading in...5
×
 

HTML5 Comprehensive Guide

on

  • 1,842 views

Quick-guide and reference material for HTML5 developers.

Quick-guide and reference material for HTML5 developers.

Statistics

Views

Total Views
1,842
Views on SlideShare
1,829
Embed Views
13

Actions

Likes
4
Downloads
87
Comments
0

2 Embeds 13

http://www.linkedin.com 10
https://www.linkedin.com 3

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

HTML5 Comprehensive Guide HTML5 Comprehensive Guide Presentation Transcript

  • HTML 5
  • What is HTML5?“Specification that defines the 5th majorrevision of the core language of theWorld Wide Web: HTML.”World Wide Web Consortium
  • What is HTML5?+ +
  • What is HTML5?New Cool
  • Who’s in charge?WHATWGW3CHTML WGBrowserVendors
  • Who’s in charge?Ian HicksonEditor of HTML5 specification
  • StandardisationEditor`s DraftFirst PublicWorking DraftLast CallCandidateRecommendationRecommendation
  • State of HTML5“So we opened a mailing list called the WHATWG to continue workon Web Forms 2.0 in public, and later that year started a new draftcalled Web Applications 1.0 into which we put many features aimedat writing Web apps, including a new version of HTML that wejokingly called HTML5…”2004Ian Hickson
  • State of HTML5
  • State of HTML5Early expectations2012 – W3C Candidate RecommendationW3C Recommendation2020?
  • State of HTML5Reality2012 – W3C Candidate RecommendationW3C Recommendation2014
  • State of HTML5Old browsers (Q1 2013)More on:www.html5test.com~ 33%IE 6-8FF 3-3.6OP 9x
  • State of HTML5Mobile PlatformsVarious degree of support in mobile operating systems.iOS Android Window Phone BlackBerry
  • State of HTML5jQuery 2.0Drops support of legacy browsers
  • State of HTML5“JQuery 2.0 now has more patches andshims for Chrome, Safari, and Firefox thanfor Internet Explorer.”Dave MethvinPresident, jQuery Foundation
  • State of HTML5WebNativeClassicWebDesktop(PC)RIA“HTML5”Web
  • State of HTML5Already moved to HTML5
  • State of HTML5“When I`m introspective about last few years I think thebiggest mistake we made as a company was betting toomuch on HTML5 as opposed to native… because it justwasn`t there. … We burned two years. It`s really painful.”Mark ZuckerbergSEO of Facebook, September 2012
  • Goals of HTML5Native MultimediaProgrammatic ContextEnhanced Web Semantics“Plug-in free” Development
  • Goals of HTML5Adobe FlashWhat is wrong with Adobe Flash?Lot of security vulnerabilitiesLow performance on older machinesDisallowed on mobile devicesRequires user to install separate plug-in
  • Goals of HTML5SilverlightWhat is wrong with Silverlight?Tied to WindowsRequires user to install separate plug-inHistorical dislike of Microsoft
  • State of HTML5Be pragmaticStabilityUse what workstodayGranularityUse what you needRationalityWeb Standards notalways 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 interestingis we actually have more people on a daily basis usingmobile Web Facebook than we have using our iOS andAndroid apps combined. So mobile Web is a big thing forus.”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!
  • HTML5ToolsVisual Studio 2012 with WebEssentials.For .NET DevelopersExpression WebFor non .NET DevelopersAdobe DreamweaverAptana StudioJetBrains WebStorm
  • HTML5Storage API`sWeb SQL IndexedDBWeb StorageLocal Storage Session Storage
  • Web StorageLocal StoragePersistent store for up to 5 MiB of dataon users local machine (10 MiB for IE)Essential detailsNever transferred to server side (no-cookies)Accessible from JavaScriptStore for Key-Value pairs of stringsImportant notesObjects should be stringifyed prior tosaving to localStorageIt is allowed for browser to clearlocalStorage without user permissionGo to fullspecification
  • Web StorageSession StorageNon-Persistent store for up to 5 MiB ofdata on users local machine (10 MiB for IE)Essential detailsGo to fullspecificationData accessible only during currentsession (browser tabs)Shares API with localStorage
  • Web StorageLocal Storage & Session StoragesetItem(key, value) - to set something to the browsers storageAPIGo to fullspecificationgetItem(key) – to get value from storageremoveItem(key) – to remove item from storageclear() – to clear storage
  • Web SQLEssentialsWhat`s is Web SQL?Go to fullspecificationWeb SQL Database is a web page API for storing data in databases thatcan be queried using a variant of SQLFull power of relational database on client sideSupport for transactionsSpecification based on SQLiteSynchronous and asynchronous API
  • Web SQLWhat`s the state of Web SQL?Go to fullspecificationDeprecated! 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), butW3C need multiple independent implementations to proceed along astandardization path.Essentials
  • Web SQLGo to fullspecificationopenDatabase – opens or creates databaseAPItransaction – creates transactionexecuteSql – used for executing SQL read and write statements
  • IndexedDBEssentialsWhat`s is IndexedDB?Go to fullspecificationIndexedDB is an API for client-side storage of significant amounts ofstructured dataIt`s an object store, but it`s not a relational database.Support for transactionsSupport for indexesSynchronous and asynchronous API
  • IndexedDBEssentialsSpecific terms of IndexedDBGo to fullspecificationDatabase comprises one or more object stores which hold the datastored in the databaseObject Store is the primary storage mechanism for storing data in adatabaseTransaction is used to interact with the data in a databaseRequest represents one read or write operation
  • HTML5Native multimediaMultimediaVideo Audio
  • Native MultimediaEssentialsAbstract MediaElementAudio & Video has common APIFirst class citizen of DOM
  • Application Programming InterfaceNative MultimediaProgrammatic ContextGo to fullspecificationEventsNetwork-relatedBufferinglevelPlayback control andfeature detection
  • Native MultimediaEventsGo to fullspecificationLoadstart Progress Suspend AbortError Emptied StalledNetwork-relatedloadedmetadata loadeddata waitingplaying canplay canplaythroughBuffering level
  • Native MultimediaJavaScript & CSSGo to fullspecificationFirst-class DOM citizen and can be styles with CSS3Exposes properties and functions to JavaScriptProperties FunctionsplaybackRatevolumemutednetworkStatereadyStatecurrentTime playpauseload
  • Native MultimediaFormat SupportGo to fullspecification“…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
  • AudioEssentialsBuilt in tag <audio> for embedding audio playerNatively support – require no plug-insOut of the box user interfaceAPI for controlling audio playbackGo to fullspecification
  • AudioEssentialsGo to fullspecificationAttributes of <audio> tagSrc - media content sourcePreload - attribute is intended to provide a hint to the user agent about what theauthor thinks will lead to the best user experience.None – do not preloadMetadata – preload metadata onlyAuto – let browser decideControls – specifies whether built-in controls visible or notLoop - indicates that the media element should to seek back to the startCrossorigin - indicates that audio file is being served from different origin
  • AudioEssentialsGo to fullspecificationTools of the DevilLoop - indicates that the media element should to seek back to the startAutoplay - indicates that the media element should automatically startplayback once its fully loaded
  • AudioLook & FeelGo to fullspecificationHow 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 ContextGo to fullspecificationplay - to play audioAPIpause – to pause audiocanPlayType(type) – determines whether type supported by user agentbuffered – attribute that specifies the start and end time of the bufferedpart of the file
  • AudioFormat SupportGo to fullspecificationMP3 WebM OGG AAC
  • VideoEssentialsBuilt in tag <video> for embedding video playerNatively support – require no plug-insOut of the box user interfaceAPI for controlling video playbackGo to fullspecification
  • VideoVideo formatsGo to fullspecificationMPEG4+WebM+OGG+
  • VideoEssentialsGo to fullspecificationAttributes of <video> tagSrc - media content sourcePreload - attribute is intended to provide a hint to the user agent about what theauthor thinks will lead to the best user experience.None – do not preloadMetadata – preload metadata onlyAuto – let browser decideControls – specifies whether standard controls visible or notPoster – image to show while no video data is available
  • VideoLook & FeelGo to fullspecificationHow 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>
  • VideoIssuesGo to fullspecificationFullscreen playingLive StreamingPatchy browser support
  • CanvasEssentialsGo to fullspecificationHTML5 element that allows for dynamic, scriptable rendering of 2Dshapes and bitmapsImmediate mode renderingRich API: 45 methods, 21 attributesFuture plans for 3D rendering
  • CanvasGo to fullspecificationAPIApplication Programming InterfaceStateTransformationsCompositingColor & StylesLine caps/joinsShadowsRectanglesPath APITextPixel manipulationFocus managementDrawing images
  • CanvasHistoryGo to fullspecificationDeveloped as platform forOSX Dashboard Widgetsin 2004
  • CanvasUse casesGo to fullspecificationData visualization
  • CanvasUse casesGo to fullspecificationAnimated graphics
  • CanvasUse casesGo to fullspecificationWeb Applications
  • CanvasUse casesGo to fullspecificationGames
  • CanvasMarkupGo to fullspecificationWhat the markup is?<canvas width=‘800’ height=‘600’>Your browser doesn`t support canvas.</canvas>
  • CanvasCoordinate SystemGo to fullspecification(0, 0) XY
  • CanvasRendering ContextGo to fullspecification2D RenderingContextEverything is drawn onto 2Drendering context that is tied toCanvas instance
  • CanvasRendering ContextGo to fullspecificationContext instance can be preservedand passed around the appHow to get context?var canvas = document.getElementById(‘canvas’)var context = canvas.getContext(‘2d’)
  • CanvasDrawing ModelGo to fullspecificationHow to change color?var canvas = document.getElementById(‘canvas’)var context = canvas.getContext(‘2d’)context.fillStyle = ‘black’;context.strokeStyle = ‘white’;
  • CanvasDrawing ModelGo to fullspecificationfillRect - draws a rectangle using current fill styleSimple shapesstrokeRect – draws the outline of a rectangle using the current stroke styleclearRect – clears all pixels within the given rectangle
  • CanvasDrawing ModelGo to fullspecificationComplex shapesA new patch should be created for each complex shapePaths are a list of subpathSubpaths are one or more points connected by straight or curved linesRendering context has reference to current active path
  • CanvasDrawing ModelGo to fullspecificationComplex shapesbeginPath – resets the current pathclosePath – closes the current subpath and starts a new onefill – fills the subpaths with the current fill stylestroke – outlines the subpaths with the current stroke style
  • CanvasDrawing ModelGo to fullspecificationComplex shapeslineTo – draws a straight line from the previous pointrect – adds a new closed rectangular subpatharc – adds a subpath along the circumference of the described circle,withing the angles definedarcTo – adds a subpath connecting two points by an arc of the definedradius
  • CanvasDrawing ModelGo to fullspecificationTransformationsAffects shapes and paths drawn after the transformationShorthand methods for translation, scaling, rotationTransformation matrices are allowed
  • CanvasDrawing ModelGo to fullspecificationTransformationstranslate – moves coordinate system by specified offsetrotate – rotates coordinate system by specified anglescale – scales coordinate system by specified factortransform – multiplies current transformation matrix with specified onesetTransform – sets transformation matrix directly
  • CanvasDrawing ModelGo to fullspecificationctx.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 ModelGo to fullspecificationThe 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 ManagementGo to fullspecificationctx.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
  • CanvasCompositionGo to fullspecificationCompositing it the control of transparency and layering of objectsControlled by globalAlpha and globalCompositeOperationattributes
  • CanvasCompositionGo to fullspecification
  • CanvasDrawing ModelGo to fullspecificationFirefox, Opera and Internet Explorer follow the drawing model asdescribed in the spec.Safari and Chrome have a slightly different drawing model behavior.DO: Check if you’re composition is impacted by this interoperabilityissue.
  • CanvasPerformanceGo to fullspecificationNot all operations were made equal. Some are more expensive thanothersShadows, clipping and composition operations are more expensive asthey require an additional intermediate.DON’T: Create thousands of small objects with clipping, shadows orcompositions effects.
  • CanvasSecurity ModelGo to fullspecificationCanvas allows reading and writing pixels to the screenYou can also save the Canvas to a file via toDataURL()Canvas PNG File
  • Canvas also allows drawing cross-domain images/videosHowever, it has built-in security protection against third-parties savingcross-domain pixelsCanvasSecurity ModelGo to fullspecificationCanvasPNG File
  • CanvasSecurity ModelGo to fullspecificationCanvas 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 theCanvas pixels if the Canvas origin-clean is false:toDataURL()getImageData()
  • Animation Frame APIEssentialsGo to fullspecificationAPI for getting precise animation updatesUser Agent schedules updates in sync with internal redraw routinesAutomatic management of update time and low-power mode
  • Animation Frame APIGo to fullspecificationrequestAnimationFrame – requests repaint callback to be scheduledAPIcancelAnimationFrame – cancels repaint callback request
  • HTML5Media CaptureUser MediaAPIHTML MediaCapture
  • HTML Media CaptureEssentialsNative media capture mechanismExtends file inputAllows to capture audio, video and photo
  • HTML Media CaptureMarkupWhat 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 byaccept attributeMedia type controlled bycapture attribute
  • User Media APIEssentialsAPI that allows to capture media streamsDesigned to interoperate with related specsAllows to capture audio, video and photo
  • User Media APIEssentialsHigh level abstraction for streaming dataCan be passed around to different APIsContains audio and video tracksMedia StreamMedia Stream TrackHigh level abstraction for media stream source
  • User Media APIMedia Stream
  • User Media APIProgrammatic ContextGo to fullspecificationgetUserMedia - to start capturing media streamAPI
  • HTML5Audio ProcessingWeb AudioAPIAudio DataAPIJavaScriptDSP
  • JavaScript DSPEssentialsByte-level manipulations with encoded audio dataGetting audio data via XMLHttpRequest or File APIRequires knowledge of DSP and audio formats encodingExtension: Firefox allows access to PCM data
  • Web Audio APIWhy?<audio> hides the steps of loading, decoding and playingNo standard way to access raw PCM dataNo fine-grained timingNo concept of position and direction of sources and listenersHard to analyze and visualize data on the fly
  • Web Audio APIEssentialsHigh-level API for processing and synthesizing audioGives fine grained control over audio processing and playback
  • Web Audio APIReal-time processingand synthesizing audioCapabilitiesAn audio pipeline and routing systemfor effects and filters
  • Web Audio APIAccess to raw PCM dataCapabilities
  • Web Audio APIPrecise scheduling ofaudio playbackCapabilities
  • Web Audio APIAudio ContextAbstract representation of audiosignal graph and connectionsbetween AudioNodes
  • Web Audio APIAudio ContextAPIdestination – audio node that represents actual hardwaresampleRate – the sample rate at which Audio Context handles audiocurrentTime – time in seconds tied to hardware clocklistener – an audio listener that is used for 3D spatialization
  • Web Audio APIAudio NodeBuild block of audio graphAudio node representsSourceDestinationIntermediate processing moduleSet of predefined Audio Nodes as well as ScriptProcessorNode
  • Web Audio APIAudio NodeAudioDestinationNode AudioBufferSourceNode MediaElementAudioSourceNodeMediaStreamAudioSourceNode MediaStreamAudioDestinationNode ScriptProcessorNode Audio Effect Nodes
  • Web Audio APIAudio BufferRepresents in-memory audio assetContains IEEE 32-bit linear PCM with a nominal range of -1 -> +1Contains one or more channelsTypically expected that length of PCM data would be less than a minuteLong audio tracks can be served via MediaElementAudioSourceNode
  • HTML53DWebGLImage-based 3DCSS3 3DTransformsSoftware renderingon Canvas
  • HTML5Image-based 3DSet of prerendered imagesHigh degree of browser supportTerrific amount of data to loadNo client side customizations
  • Image-based 3DImage-based 3DFast image switches may cause flickeringRendering to Canvas may give significant performance boost
  • HTML5Software RenderingRendering and computations are made on CPUManual manipulations with Pixel and Vertex dataCanvas as rasterization surface
  • Software RenderingPerformanceSoftware rendering is inherently slowGood enough for simple scenesMobile devices are still a concern
  • HTML5CSS3 TransformsDisplay-time transformations of any HTML contenttransforms do not affect layout3D Transformstranslate, scale, rotate, skew in X, Y & Zperspective
  • CSS3 TransformsEssentialsRendering and computations are made on GPUApplies to any DOM elementDeclarative and programmatic control
  • HTML5CSS Custom ShadersUser supplied program for GPU programmingExecutes in parallelSource of awesome visual effectsProgrammed in GLSL
  • CSS Custom ShadersShowcase
  • CSS Custom ShadersRendering Pipeline
  • CSS Custom ShadersTypesFragmentShaderVertexShader
  • CSS Custom ShadersFragment ShaderGPU program for pixel color manipulationThe result is a pixel colorExecutes in parallel on GPU infrastructureCurrently there is no way to set via gl_FragColor
  • Fragment ShaderSampleprecision 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 ShaderResponsible for mesh deformationsThe result is a vertex positionExecutes in parallel on GPU infrastructure
  • Vertex ShaderSampleprecision mediump float;attribute vec4 a_position;uniform mat4 u_projectionMatrix;void main() {gl_Position = u_projectionMatrix * a_position;}Projection matrix is supplied by aweb 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);}CSSprecision mediump float;uniform float amount;void main(){}Fragment Shader
  • WebGLEssentialsIt is a software library that extends the capability of the JavaScriptto allow it to generate 3D graphicsUses canvas as rendering surfaceBased on OpenGL ES 2.0
  • WebGLStandard
  • WebGLSupport“We believe that WebGL will likely become an ongoingsource of hard-to-fix vulnerabilities. In its current form,WebGL is not a technology Microsoft can endorse from asecurity perspective.”MicrosoftJune 16, 2011
  • WebGLSupport“I agree with Microsoft’s assessment that WebGL is asevere security risk. The gfx driver culture is not theculture of security.”John CarmackCo-founder of Id Software, June 2011
  • WebGLArchitecture
  • Typed ArraysEssentialsEfficient way to pass data into API`sC-like arraysMemory can be passed directly to native API`s
  • Typed ArraysArray BufferAbstract representation of binary dataServes as a data-source for typed arraysIntegrated with other HTML API`s
  • Typed ArraysArray Buffer ViewInt8Array Uint8Array Int16Array Uint16Array Int32ArrayUint32Array Float32Array Float64Array Uint8ClampedArray
  • Typed ArraysData ViewSimplifies manipulations with heterogeneous typesSupports big and little endianBe careful with alignment
  • Typed ArraysInteroperabilityWebGL Canvas 2D File APIWebSocketsXHR2MediaSourceTransferable objects
  • Same Origin PolicyGo to fullspecificationSecurityBrowser-level FirewallProhibits sending security sensitive information to foreign locationsProhibits read of resources from foreign originPrimary security barrier against XSS and Cookie stealing attacksWhat is same origin policy?
  • Same Origin PolicyGo to fullspecificationSecurityWhat origins are foreign?http://www.example.comSame protocol and host but different porthttp://www.example.com:81Different protocolhttps://www.example.comDifferent hosthttp://en.example.com
  • Web MessagingEssentialsGo to fullspecificationMechanism for cross-document communicationSupport for cross-origin communicationAPI for exchanging plain text messages and structured dataWhat is Web Messaging?
  • Web MessagingCommunicationGo to fullspecificationWindowobjectMessageChannel
  • Web MessagingEssentialsGo to fullspecificationThe end of iframe hacks!
  • Web MessagingAPIGo to fullspecificationpostMessage() – to post message to windowMessage event – event raised when new message arrived
  • Web WorkersGo to fullspecificationJavaScript is inherently single threadedAsynchronous through single message loopNo concurrency, no thread synchronizationMotivation
  • Web WorkersIssueGo to fullspecification“[JavaScript] that executes in whole seconds is probablydoing something wrong...”Brendan EichCreator of JavaScript,Mozilla Foundation
  • Web WorkersEffectGo to fullspecification
  • Web WorkersOld-school solutionsGo to fullspecificationPartitionwork withtimersOffloadwork toserver
  • Web WorkersEssentialsGo to fullspecificationJavaScript native ‘threading’ mechanismTrue parallelismDesigned to be long-livedHigh startup cost performance and memory costWhat are Web Workers?
  • Web WorkersEssentialsGo to fullspecificationLoaded from separate file or BlobCommunication with parent script through messages and eventsCan be terminated from inside and outsideDue to their multi-threaded behavior, web workers only has access to asubset of DOM and BOM featuresHow it works?
  • Web WorkersScopeGo to fullspecificationThe navigator objectThe location object (read-only)XMLHttpRequestsetTimeout(), setInterval()The application cacheImporting external scripts using the importScripts() methodSpawning other Web WorkersFeatures Available to Workers
  • Web WorkersScopeGo to fullspecificationDOM and BOMwindow objectdocument objectparent objectFeatures Unavailable to Workers
  • Web WorkersTypesGo to fullspecificationDedicated Shared
  • Web WorkersTransferable ObjectsGo to fullspecificationStructured data can be passed without copyingHuge performance winSupported structured objects:ArrayBufferMessagePortCanvasProxy
  • Web WorkersTransferable ObjectsGo to fullspecification
  • HTML5Go to fullspecificationReal-time CommunicationsHTTP protocol has one request – one resource semanticsNo built-in mechanism for Push NotificationsSemi-duplex communicationsOverhead of HTTP headers
  • Real-timeGo to fullspecificationUse casesLive feeds
  • Real-timeGo to fullspecificationUse casesMultiplayer games
  • Real-timeGo to fullspecificationUse casesLive sync applications
  • Real-timeGo to fullspecificationWorkaroundsPolling Comet
  • Real-timeGo to fullspecificationPollingPeriodic HTTP requestsHigh server workloadHigh latencyHigh degree of support across different browsers
  • PollingGo to fullspecificationInteraction diagram
  • PollingGo to fullspecificationNetwork throughput
  • Real-timeGo to fullspecificationCometPeriodic long-lived HTTP requestsReduced trafficReduced server workloadOverhead of HTTP headersPossible difficulties with proxies and load balancers
  • CometGo to fullspecificationInteraction diagram
  • CometGo to fullspecificationTypesLongpollingHTTPStreaming
  • Web SocketsGo to fullspecificationEssentialsFull-duplex socket connectionWeb Socket protocol v13 (RFC 6455) instead of HTTPUses HTTP for connection establishmentLow-latency client-server communication technology
  • Web SocketsGo to fullspecificationConnection EstablishmentRuns via port 80/443 to simplify firewalls traversalPseudo schemes: ws, wssConnection established by “upgrading” from HTTP to WebSocketprotocol
  • Web SocketsGo to fullspecificationOpening handshakeGET /chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Origin: http://example.comSec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13Client sends GET or CONNECTrequest to Web Socket endpointUpgrade header indicates willingto upgrade connection fromHTTP to WebSocket
  • Web SocketsGo to fullspecificationOpening handshakeHTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Server responds with 101 statuscode and connection upgradeheaderFrom now on Web Socketprotocol will be used instead ofHTTP
  • Web SocketsGo to fullspecificationAPIvar connection = new WebSocket(ws://html5rocks.websocket.org/echo);ConnectionCommunication// When the connection is open, send some data to theserverconnection.onopen = function () {// Send the message Ping to the serverconnection.send(Ping);};// Log errorsconnection.onerror = function (error) {// Log messages from the serverconsole.log(WebSocket Error + error);};connection.onmessage = function (e) {console.log(Server: + e.data);};
  • Server-sent EventsGo to fullspecificationEssentialsSupport for auto reconnectSupport for event idsRequires Content-Type: text/event-streamBrowser built-in long polling mechanism
  • Server-sent EventsGo to fullspecificationEssentialsdata: This is the first message.data: This is the second message, itdata: has two lines.data: This is the third message.Responseevent: adddata: 73857293event: removedata: 2153event: adddata: 113411Response with named Events
  • XHR Level 2Go to fullspecificationEssentialsWhat is XHR?API for sending HTTP and HTTPS requests directly to Web ServerSupports plain text and structured response formatsInteraction without page refreshBasement of AJAX
  • XHR Level 2Go to fullspecificationInteraction ModelAJAXJavaScriptDocumentObjectModelXHRAsynchronousWeb callsDHTMLmanipulations
  • XHR Level 2Go to fullspecificationSecurityStrong security concernsSame origin policyCross-origin resourcesharing policy
  • XHR Level 2Go to fullspecificationSecurityCross-origin communication scenariosJSONP CORSBlindProxiesWebMessagingIframehacksHTTPforgery
  • XHR Level 2Go to fullspecificationSecurityWay for a web server to allow its resources to be accessed by a web pagefrom a different domainRequires server & client side supportServer side decides which origins are allowedHTTP header based negotiationWhat is cross-origin resource sharing?
  • XHR Level 2Go to fullspecificationSecurity
  • XHR Level 2Go to fullspecificationSecurityRequestGET http://photos.contoso.com/albums HTTP/1.1Origin: http://www.contoso.comOrigin header specifies that this isCORS aware request.ResponseHTTP/1.1 200 OKAccess-Control-Allow-Origin: http://www.contoso.comServer respond with special headerthat allows browser to consume suchresponse
  • XHR Level 2Go to fullspecificationSecurityRequestOPTIONS http://photos.contoso.com/albums HTTP/1.1Origin: http://www.contoso.comAccess-Control-Request-Method: PUTIn case of non-safe methods webbrowser should send preflight requestprior to sending actual requestResponseHTTP/1.1 200 OKAccess-Control-Allow-Origin: http://www.contoso.comAccess-Control-Allow-Methods: PUTServer respond with special headerthat allows browser to make actualrequest
  • XHR Level 2Go to fullspecificationFeaturesCross-originrequestsUploadingprogresseventsUploadingdownloadingstructureddata
  • XHR Level 2Go to fullspecificationFeaturesStructured dataAllows to get resources as structured objectAllows to post data as structured objectControlled via responseType propertyNew response property to consume resource in structured format
  • XHR Level 2Go to fullspecificationFeaturesStructured formats (upload)ArrayBuffer – generic fixed-length binary data bufferFormData – object based representation of form fieldsBlob – url accessible container for binary dataDocumentDOMString – plain text response
  • XHR Level 2Go to fullspecificationFeaturesStructured formats (download)arraybuffer – generic fixed-length binary data bufferblob – url accessible container for binary datadocumenttext – plain text responsejson – json string converted into object
  • XHR Level 2Go to fullspecificationFeaturesStructured 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
  • GeolocationEssentialsGo to fullspecificationMechanism for determining user geographic coordinatesAvailable on desktop and mobile devicesUses GPS, A-GPS, Wi-Fi hotspots or IP address range to determine currentcoordinatesEasy to use JavaScript APIStrong security concernsWhat is Geolocation?
  • GeolocationAPIGo to fullspecificationMain object – navigator.geolocationgetCurrentPosition – gets current position & speed (if possible)watchPosition – track position changesclearWatch – stop tracking position changes
  • Device OrientationEssentialsMechanism for determining Euler`s angles (rotation around X,Y, Z)Supported on broad variety of mobile devicesWhat is device orientation?The deviceorientation event with orientation data passed alongThe devicemotion event with orientation and acceleration datapassed along
  • Application CacheEssentialsGo to fullspecificationSoftware storage feature which provides the ability to access a webapplication even without a networkControlled by a plain text file called a cache manifestCan be managed by JavaScript APIWhat is Web Application Cache?
  • Application CacheManifest fileGo to fullspecificationContains a list of resources to be stored for use when there is no networkconnectivityDefines conditions for cachingConsist of sectionsCACHE – a list of explicit urls to request and storeFALLBACK - What to do when an offline user attempts toaccess an uncached fileNETWORK – Which resources are available only when online
  • Application CacheManifest fileGo to fullspecification<!DOCTYPE HTML><html manifest="/cache.appcache"><body> … </body></html>Page markupCACHE MANIFEST# This is a commentCACHE:/css/screen.css/css/offline.css/js/screen.js/img/logo.pnghttp://example.com/css/styles.cssFALLBACK:/ /offline.htmlNETWORK:*Manifest file
  • CSS 3
  • Graphics FeaturesTransparencycolor specification with alpha, opacity propertyRound cornersborder-radiusShadowsbox-shadow, text-shadowBackground gradientslinear, radialTypographyWeb Open Font Format (WOFF) fonts
  • 2D & 3D TransformsDisplay-time transformations of any HTML contenttransforms do not affect layout2D Transformstranslate, scale, rotate, skew3D Transformstranslate, scale, rotate, skew in X, Y & Zperspective
  • Animations & TransitionsTransitionssmooth animation of CSS properties from old to new valuecan be used with CSS pseudo-classes such as :hoverAnimationskeyframe-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 TagsSemantic 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 distributedindependently from the rest of the site.<aside>For content aside from the content it is placed in. The aside contentshould be related to the surrounding content<bdi>For text that should not be bound to the text-direction of its parentelements<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 theauthor, the date of the document, contact information, or copyrightinformation<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 isthe 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 valuesare 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, orany 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”divHTML4XHTML4
  • Semantic Markup<header><nav><footer><article> <aside><section>HTML5XHTML5
  • Semantic Markup
  • Input Types13 new input typesBuilt-in client-side validationPoor support in desktop browsersSee browser compatibilityinformation
  • Input Typessearch tel url email datetimedate month week timedatetime-localnumber range color
  • HTML5Feature detectionNever use navigator.userAgent browser detection hackNever use conditional comment in Internet ExplorerUse feature detecting instead of browser detection when possibleConsider graceful fallbackUse Modernizr
  • Feature detectionModernizrModernizr is a small JavaScript Library that detects the availabilityof native implementations for next-generation web technologiesWhat is Modernizr?Why Modernizr?Easy to usePowerfull feature detection library
  • Feature detectionModernizrModernizr does its “magic” by creating an element, setting a specificstyle instruction on that element and then immediately retrieving itHow it works?Feature detection results available to developer via JavaScriptModernizr object and classes applied to HTML DOM element
  • Feature detectionModernizrHow it looks like?/* In your CSS: */.no-audio #music {display: none; /* Dont 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 contenthttp://www.html5rocks.comHTML5 news, demos, presentationshttp://www.html5doctor.comLot of HTML5 tutorials, articleshttp://ie.microsoft.com/testdrive/Graphics/hands-on-css3/HTML5 Hands-On
  • THE END