HTML5 Comprehensive Guide


Published on

Quick-guide and reference material for HTML5 developers.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

HTML5 Comprehensive Guide

  1. 1. HTML 5
  2. 2. What is HTML5?“Specification that defines the 5th majorrevision of the core language of theWorld Wide Web: HTML.”World Wide Web Consortium
  3. 3. What is HTML5?+ +
  4. 4. What is HTML5?New Cool
  5. 5. Who’s in charge?WHATWGW3CHTML WGBrowserVendors
  6. 6. Who’s in charge?Ian HicksonEditor of HTML5 specification
  7. 7. StandardisationEditor`s DraftFirst PublicWorking DraftLast CallCandidateRecommendationRecommendation
  8. 8. 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
  9. 9. State of HTML5
  10. 10. State of HTML5Early expectations2012 – W3C Candidate RecommendationW3C Recommendation2020?
  11. 11. State of HTML5Reality2012 – W3C Candidate RecommendationW3C Recommendation2014
  12. 12. State of HTML5Old browsers (Q1 2013)More 33%IE 6-8FF 3-3.6OP 9x
  13. 13. State of HTML5Mobile PlatformsVarious degree of support in mobile operating systems.iOS Android Window Phone BlackBerry
  14. 14. State of HTML5jQuery 2.0Drops support of legacy browsers
  15. 15. State of HTML5“JQuery 2.0 now has more patches andshims for Chrome, Safari, and Firefox thanfor Internet Explorer.”Dave MethvinPresident, jQuery Foundation
  16. 16. State of HTML5WebNativeClassicWebDesktop(PC)RIA“HTML5”Web
  17. 17. State of HTML5Already moved to HTML5
  18. 18. 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
  19. 19. Goals of HTML5Native MultimediaProgrammatic ContextEnhanced Web Semantics“Plug-in free” Development
  20. 20. 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
  21. 21. Goals of HTML5SilverlightWhat is wrong with Silverlight?Tied to WindowsRequires user to install separate plug-inHistorical dislike of Microsoft
  22. 22. State of HTML5Be pragmaticStabilityUse what workstodayGranularityUse what you needRationalityWeb Standards notalways fit
  23. 23. 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
  24. 24. 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!
  25. 25. HTML5ToolsVisual Studio 2012 with WebEssentials.For .NET DevelopersExpression WebFor non .NET DevelopersAdobe DreamweaverAptana StudioJetBrains WebStorm
  26. 26. HTML5Storage API`sWeb SQL IndexedDBWeb StorageLocal Storage Session Storage
  27. 27. 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
  28. 28. 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
  29. 29. 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
  30. 30. 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
  31. 31. 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
  32. 32. Web SQLGo to fullspecificationopenDatabase – opens or creates databaseAPItransaction – creates transactionexecuteSql – used for executing SQL read and write statements
  33. 33. 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
  34. 34. 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
  35. 35. HTML5Native multimediaMultimediaVideo Audio
  36. 36. Native MultimediaEssentialsAbstract MediaElementAudio & Video has common APIFirst class citizen of DOM
  37. 37. Application Programming InterfaceNative MultimediaProgrammatic ContextGo to fullspecificationEventsNetwork-relatedBufferinglevelPlayback control andfeature detection
  38. 38. Native MultimediaEventsGo to fullspecificationLoadstart Progress Suspend AbortError Emptied StalledNetwork-relatedloadedmetadata loadeddata waitingplaying canplay canplaythroughBuffering level
  39. 39. Native MultimediaJavaScript & CSSGo to fullspecificationFirst-class DOM citizen and can be styles with CSS3Exposes properties and functions to JavaScriptProperties FunctionsplaybackRatevolumemutednetworkStatereadyStatecurrentTime playpauseload
  40. 40. 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
  41. 41. AudioEssentialsBuilt in tag <audio> for embedding audio playerNatively support – require no plug-insOut of the box user interfaceAPI for controlling audio playbackGo to fullspecification
  42. 42. 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
  43. 43. 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
  44. 44. 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>
  45. 45. 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
  46. 46. AudioFormat SupportGo to fullspecificationMP3 WebM OGG AAC
  47. 47. VideoEssentialsBuilt in tag <video> for embedding video playerNatively support – require no plug-insOut of the box user interfaceAPI for controlling video playbackGo to fullspecification
  48. 48. VideoVideo formatsGo to fullspecificationMPEG4+WebM+OGG+
  49. 49. 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
  50. 50. 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>
  51. 51. VideoIssuesGo to fullspecificationFullscreen playingLive StreamingPatchy browser support
  52. 52. 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
  53. 53. CanvasGo to fullspecificationAPIApplication Programming InterfaceStateTransformationsCompositingColor & StylesLine caps/joinsShadowsRectanglesPath APITextPixel manipulationFocus managementDrawing images
  54. 54. CanvasHistoryGo to fullspecificationDeveloped as platform forOSX Dashboard Widgetsin 2004
  55. 55. CanvasUse casesGo to fullspecificationData visualization
  56. 56. CanvasUse casesGo to fullspecificationAnimated graphics
  57. 57. CanvasUse casesGo to fullspecificationWeb Applications
  58. 58. CanvasUse casesGo to fullspecificationGames
  59. 59. CanvasMarkupGo to fullspecificationWhat the markup is?<canvas width=‘800’ height=‘600’>Your browser doesn`t support canvas.</canvas>
  60. 60. CanvasCoordinate SystemGo to fullspecification(0, 0) XY
  61. 61. CanvasRendering ContextGo to fullspecification2D RenderingContextEverything is drawn onto 2Drendering context that is tied toCanvas instance
  62. 62. 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’)
  63. 63. CanvasDrawing ModelGo to fullspecificationHow to change color?var canvas = document.getElementById(‘canvas’)var context = canvas.getContext(‘2d’)context.fillStyle = ‘black’;context.strokeStyle = ‘white’;
  64. 64. 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
  65. 65. 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
  66. 66. 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
  67. 67. 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
  68. 68. CanvasDrawing ModelGo to fullspecificationTransformationsAffects shapes and paths drawn after the transformationShorthand methods for translation, scaling, rotationTransformation matrices are allowed
  69. 69. 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
  70. 70. 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.
  71. 71. 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.
  72. 72. CanvasState ManagementGo to;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
  73. 73. CanvasCompositionGo to fullspecificationCompositing it the control of transparency and layering of objectsControlled by globalAlpha and globalCompositeOperationattributes
  74. 74. CanvasCompositionGo to fullspecification
  75. 75. 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.
  76. 76. 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.
  77. 77. 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
  78. 78. Canvas also allows drawing cross-domain images/videosHowever, it has built-in security protection against third-parties savingcross-domain pixelsCanvasSecurity ModelGo to fullspecificationCanvasPNG File
  79. 79. 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()
  80. 80. 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
  81. 81. Animation Frame APIGo to fullspecificationrequestAnimationFrame – requests repaint callback to be scheduledAPIcancelAnimationFrame – cancels repaint callback request
  82. 82. HTML5Media CaptureUser MediaAPIHTML MediaCapture
  83. 83. HTML Media CaptureEssentialsNative media capture mechanismExtends file inputAllows to capture audio, video and photo
  84. 84. 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
  85. 85. User Media APIEssentialsAPI that allows to capture media streamsDesigned to interoperate with related specsAllows to capture audio, video and photo
  86. 86. 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
  87. 87. User Media APIMedia Stream
  88. 88. User Media APIProgrammatic ContextGo to fullspecificationgetUserMedia - to start capturing media streamAPI
  89. 89. HTML5Audio ProcessingWeb AudioAPIAudio DataAPIJavaScriptDSP
  90. 90. 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
  91. 91. 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
  92. 92. Web Audio APIEssentialsHigh-level API for processing and synthesizing audioGives fine grained control over audio processing and playback
  93. 93. Web Audio APIReal-time processingand synthesizing audioCapabilitiesAn audio pipeline and routing systemfor effects and filters
  94. 94. Web Audio APIAccess to raw PCM dataCapabilities
  95. 95. Web Audio APIPrecise scheduling ofaudio playbackCapabilities
  96. 96. Web Audio APIAudio ContextAbstract representation of audiosignal graph and connectionsbetween AudioNodes
  97. 97. 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
  98. 98. Web Audio APIAudio NodeBuild block of audio graphAudio node representsSourceDestinationIntermediate processing moduleSet of predefined Audio Nodes as well as ScriptProcessorNode
  99. 99. Web Audio APIAudio NodeAudioDestinationNode AudioBufferSourceNode MediaElementAudioSourceNodeMediaStreamAudioSourceNode MediaStreamAudioDestinationNode ScriptProcessorNode Audio Effect Nodes
  100. 100. 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
  101. 101. HTML53DWebGLImage-based 3DCSS3 3DTransformsSoftware renderingon Canvas
  102. 102. HTML5Image-based 3DSet of prerendered imagesHigh degree of browser supportTerrific amount of data to loadNo client side customizations
  103. 103. Image-based 3DImage-based 3DFast image switches may cause flickeringRendering to Canvas may give significant performance boost
  104. 104. HTML5Software RenderingRendering and computations are made on CPUManual manipulations with Pixel and Vertex dataCanvas as rasterization surface
  105. 105. Software RenderingPerformanceSoftware rendering is inherently slowGood enough for simple scenesMobile devices are still a concern
  106. 106. HTML5CSS3 TransformsDisplay-time transformations of any HTML contenttransforms do not affect layout3D Transformstranslate, scale, rotate, skew in X, Y & Zperspective
  107. 107. CSS3 TransformsEssentialsRendering and computations are made on GPUApplies to any DOM elementDeclarative and programmatic control
  108. 108. HTML5CSS Custom ShadersUser supplied program for GPU programmingExecutes in parallelSource of awesome visual effectsProgrammed in GLSL
  109. 109. CSS Custom ShadersShowcase
  110. 110. CSS Custom ShadersRendering Pipeline
  111. 111. CSS Custom ShadersTypesFragmentShaderVertexShader
  112. 112. 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
  113. 113. 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 );}
  114. 114. CSS Custom ShadersVertex ShaderResponsible for mesh deformationsThe result is a vertex positionExecutes in parallel on GPU infrastructure
  115. 115. 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
  116. 116. CSS Custom ShadersSyntax#myelement {filter: custom( vertex-shader[ fragment-shader][,vertex-mesh][,params]);}How to apply shader?
  117. 117. CSS Custom ShadersVertex Creation#myelement {filter: custom( vertex-shader[ fragment-shader],4 5[,params]);}How to apply shader?
  118. 118. CSS Custom ShadersUniforms#myelement {filter: custom( vertex-shader[ fragment-shader],4 5, amount 0);}CSSprecision mediump float;uniform float amount;void main(){}Fragment Shader
  119. 119. 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
  120. 120. WebGLStandard
  121. 121. 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
  122. 122. 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
  123. 123. WebGLArchitecture
  124. 124. Typed ArraysEssentialsEfficient way to pass data into API`sC-like arraysMemory can be passed directly to native API`s
  125. 125. Typed ArraysArray BufferAbstract representation of binary dataServes as a data-source for typed arraysIntegrated with other HTML API`s
  126. 126. Typed ArraysArray Buffer ViewInt8Array Uint8Array Int16Array Uint16Array Int32ArrayUint32Array Float32Array Float64Array Uint8ClampedArray
  127. 127. Typed ArraysData ViewSimplifies manipulations with heterogeneous typesSupports big and little endianBe careful with alignment
  128. 128. Typed ArraysInteroperabilityWebGL Canvas 2D File APIWebSocketsXHR2MediaSourceTransferable objects
  129. 129. 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?
  130. 130. Same Origin PolicyGo to fullspecificationSecurityWhat origins are foreign?http://www.example.comSame protocol and host but different port protocolhttps://www.example.comDifferent host
  131. 131. Web MessagingEssentialsGo to fullspecificationMechanism for cross-document communicationSupport for cross-origin communicationAPI for exchanging plain text messages and structured dataWhat is Web Messaging?
  132. 132. Web MessagingCommunicationGo to fullspecificationWindowobjectMessageChannel
  133. 133. Web MessagingEssentialsGo to fullspecificationThe end of iframe hacks!
  134. 134. Web MessagingAPIGo to fullspecificationpostMessage() – to post message to windowMessage event – event raised when new message arrived
  135. 135. Web WorkersGo to fullspecificationJavaScript is inherently single threadedAsynchronous through single message loopNo concurrency, no thread synchronizationMotivation
  136. 136. Web WorkersIssueGo to fullspecification“[JavaScript] that executes in whole seconds is probablydoing something wrong...”Brendan EichCreator of JavaScript,Mozilla Foundation
  137. 137. Web WorkersEffectGo to fullspecification
  138. 138. Web WorkersOld-school solutionsGo to fullspecificationPartitionwork withtimersOffloadwork toserver
  139. 139. Web WorkersEssentialsGo to fullspecificationJavaScript native ‘threading’ mechanismTrue parallelismDesigned to be long-livedHigh startup cost performance and memory costWhat are Web Workers?
  140. 140. 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?
  141. 141. 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
  142. 142. Web WorkersScopeGo to fullspecificationDOM and BOMwindow objectdocument objectparent objectFeatures Unavailable to Workers
  143. 143. Web WorkersTypesGo to fullspecificationDedicated Shared
  144. 144. Web WorkersTransferable ObjectsGo to fullspecificationStructured data can be passed without copyingHuge performance winSupported structured objects:ArrayBufferMessagePortCanvasProxy
  145. 145. Web WorkersTransferable ObjectsGo to fullspecification
  146. 146. HTML5Go to fullspecificationReal-time CommunicationsHTTP protocol has one request – one resource semanticsNo built-in mechanism for Push NotificationsSemi-duplex communicationsOverhead of HTTP headers
  147. 147. Real-timeGo to fullspecificationUse casesLive feeds
  148. 148. Real-timeGo to fullspecificationUse casesMultiplayer games
  149. 149. Real-timeGo to fullspecificationUse casesLive sync applications
  150. 150. Real-timeGo to fullspecificationWorkaroundsPolling Comet
  151. 151. Real-timeGo to fullspecificationPollingPeriodic HTTP requestsHigh server workloadHigh latencyHigh degree of support across different browsers
  152. 152. PollingGo to fullspecificationInteraction diagram
  153. 153. PollingGo to fullspecificationNetwork throughput
  154. 154. Real-timeGo to fullspecificationCometPeriodic long-lived HTTP requestsReduced trafficReduced server workloadOverhead of HTTP headersPossible difficulties with proxies and load balancers
  155. 155. CometGo to fullspecificationInteraction diagram
  156. 156. CometGo to fullspecificationTypesLongpollingHTTPStreaming
  157. 157. Web SocketsGo to fullspecificationEssentialsFull-duplex socket connectionWeb Socket protocol v13 (RFC 6455) instead of HTTPUses HTTP for connection establishmentLow-latency client-server communication technology
  158. 158. Web SocketsGo to fullspecificationConnection EstablishmentRuns via port 80/443 to simplify firewalls traversalPseudo schemes: ws, wssConnection established by “upgrading” from HTTP to WebSocketprotocol
  159. 159. 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
  160. 160. 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
  161. 161. Web SocketsGo to fullspecificationAPIvar connection = new WebSocket(ws://;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: +;};
  162. 162. Server-sent EventsGo to fullspecificationEssentialsSupport for auto reconnectSupport for event idsRequires Content-Type: text/event-streamBrowser built-in long polling mechanism
  163. 163. Server-sent EventsGo to fullspecificationEssentialsdata: This is the first This is the second message, itdata: has two This is the third message.Responseevent: adddata: 73857293event: removedata: 2153event: adddata: 113411Response with named Events
  164. 164. 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
  165. 165. XHR Level 2Go to fullspecificationInteraction ModelAJAXJavaScriptDocumentObjectModelXHRAsynchronousWeb callsDHTMLmanipulations
  166. 166. XHR Level 2Go to fullspecificationSecurityStrong security concernsSame origin policyCross-origin resourcesharing policy
  167. 167. XHR Level 2Go to fullspecificationSecurityCross-origin communication scenariosJSONP CORSBlindProxiesWebMessagingIframehacksHTTPforgery
  168. 168. 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?
  169. 169. XHR Level 2Go to fullspecificationSecurity
  170. 170. XHR Level 2Go to fullspecificationSecurityRequestGET 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
  171. 171. XHR Level 2Go to fullspecificationSecurityRequestOPTIONS 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
  172. 172. XHR Level 2Go to fullspecificationFeaturesCross-originrequestsUploadingprogresseventsUploadingdownloadingstructureddata
  173. 173. 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
  174. 174. 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
  175. 175. 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
  176. 176. XHR Level 2Go to fullspecificationFeaturesStructured data var xhr = new XMLHttpRequest();, /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
  177. 177. 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?
  178. 178. GeolocationAPIGo to fullspecificationMain object – navigator.geolocationgetCurrentPosition – gets current position & speed (if possible)watchPosition – track position changesclearWatch – stop tracking position changes
  179. 179. 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
  180. 180. 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?
  181. 181. 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
  182. 182. 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.png /offline.htmlNETWORK:*Manifest file
  183. 183. CSS 3
  184. 184. Graphics FeaturesTransparencycolor specification with alpha, opacity propertyRound cornersborder-radiusShadowsbox-shadow, text-shadowBackground gradientslinear, radialTypographyWeb Open Font Format (WOFF) fonts
  185. 185. 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
  186. 186. 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
  187. 187. 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
  188. 188. Markup
  189. 189. New TagsSemantic Input types Multimedia Other
  190. 190. 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.
  191. 191. Semantic Markupdiv=”header”div=”nav”div=”footer”div=”article” div=”sidebar”divHTML4XHTML4
  192. 192. Semantic Markup<header><nav><footer><article> <aside><section>HTML5XHTML5
  193. 193. Semantic Markup
  194. 194. Input Types13 new input typesBuilt-in client-side validationPoor support in desktop browsersSee browser compatibilityinformation
  195. 195. Input Typessearch tel url email datetimedate month week timedatetime-localnumber range color
  196. 196. 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
  197. 197. 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
  198. 198. 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
  199. 199. 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>
  200. 200. LinksUseful HTML5 contenthttp://www.html5rocks.comHTML5 news, demos, presentationshttp://www.html5doctor.comLot of HTML5 tutorials, articles Hands-On
  201. 201. THE END