Marakana HTML5 Training i
Marakana HTML5 Training Marakana HTML5 Training ii
Copyright © 2011 Marakana, Inc. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of Marakana Inc. We took every precaution in preparation of this material. However, the we assumes no responsibility for errors or omis- sions, or for damages that may result from the use of information, including software code, contained herein. Firefox® is a registered trademark of the Mozilla Foundation. Opera® is a registered trademark of Opera Software. Google Chrome™ is a trademark of Google Inc. Safari® is a registered trademark of Apple Inc., registered in the U.S. and other countries. Internet Explorer® is a registered trademark of Microsoft Corporation in the United States and/or other countries. All other names are used for identification purposes only and are trademarks of their respective owners. Marakana offers a whole range of training courses, both on public and private. For list of upcoming courses, visit http://marakana.com Marakana HTML5 Training iii
Contents
1 History, Vision And Future Of HTML51 1.1 What Is HTML5?...... 1 1.2 History And Major Actors...... 1 1.2.1 A Little Retrospective...... 2 1.2.2 What Is The W3C?...... 2 1.2.3 What Is The WHATWG?...... 3 1.3 Vision And Philosophy Behind HTML5...... 3 1.3.1 Compatibility...... 3 1.3.2 Utility...... 4 1.3.3 Interoperability...... 4 1.3.4 Universal Access...... 5 1.4 Future Of HTML5...... 5 1.4.1 Timeline...... 5
2 Getting Started With HTML5 6 2.1 The State Of Browser Support...... 6 2.1.1 Browsers In Mobile Devices...... 6 2.1.2 Feature Detection...... 7 2.2 Support For Legacy Browsers...... 8 2.2.1 Graceful Degradation...... 9 2.2.2 Emulation...... 9 2.3 Developer Tools...... 9 2.4 Quiz...... 10 Marakana HTML5 Training iv
3 Structure Of A Web Page 11 3.1 HTML5 DOCTYPE...... 11 3.2 Page Encoding...... 12 3.3 HTML5 Markup...... 12 3.3.1 New And Updated Elements...... 13 3.3.2 Structural Elements...... 13 3.3.3 New Attributes...... 15 3.3.4 Deprecated Elements And Attributes...... 16 3.4 HTML5 And CSS3...... 16 3.5 Browser Support...... 17 3.6 Quiz...... 17 3.7 Lab: Converting a blog to HTML5...... 19
4 Forms 23 4.1 What Are The Needs For Web Applications?...... 23 4.2 Current Solutions...... 24 4.3 New Input Types...... 24 4.4 New Attributes...... 25 4.5 Form Validation...... 26 4.6 Browser Support...... 28 4.7 Quiz...... 28 4.8 Lab: Creating the form for our site...... 28
5 Audio And Video 32 5.1 The State of Web Audio And Video Based On Plugins...... 32 5.2 The State Of Audio And Video Codecs (e.g. H.264, WebM, etc.)...... 32 5.2.1 Video/Audio Codecs And Browser Support...... 33 5.3 New Audio/Video Markup...... 34 5.4 Attributes And Methods...... 35 5.5 Understanding Audio/Video Events...... 35 5.6 Customizing Audio/Video Controls...... 35 5.7 Quiz...... 36 5.8 Lab: Create a custom video player...... 36 Marakana HTML5 Training v
6 HTML5 Canvas 39 6.1 Overview Of Graphics In The Browser...... 39 6.1.1 Canvas Vs. SVG...... 39 6.1.2 Accessibility...... 40 6.2 Using A Canvas...... 40 6.3 Context And Coordinates...... 41 6.4 Drawing Shapes...... 41 6.5 Working With Paths...... 42 6.5.1 Drawing Straight Lines...... 42 6.5.2 Drawing Circles Or Arcs...... 43 6.6 Drawing Text...... 44 6.7 Drawing Images...... 45 6.8 Working With Pixels...... 46 6.9 Understanding Transforms...... 48 6.9.1 Translation...... 49 6.9.2 Rotation...... 50 6.9.3 Scaling...... 51 6.10 Browser Support...... 52 6.11 Quiz...... 52 6.12 Lab: Create a drawing application...... 52
7 Data Storage 55 7.1 Problems With The Existing Cookie-based Model...... 55 7.2 Hacks Prior To HTML5...... 55 7.3 New Storage Options...... 56 7.3.1 Web Storage...... 56 7.3.2 Browser Support...... 57 7.3.3 Web SQL Storage...... 57 7.3.4 Browser Support...... 59 7.4 Quiz...... 59 7.5 Lab: Playing with the localStorage ...... 59
8 HTML5 Offline Applications 60 8.1 The Need For Offline Mode...... 60 8.2 The Manifest File...... 60 8.3 The applicationCache Events...... 61 8.4 Deployments And Updates...... 63 8.5 Browser Support...... 63 8.6 Quiz...... 63 8.7 Lab: Putting an application offline...... 63 Marakana HTML5 Training vi
9 HTML5 Geolocation 68 9.1 Introduction To Geolocation...... 68 9.2 Privacy Considerations...... 68 9.3 Many Ways To Get User Location...... 69 9.4 Two Main Methods...... 69 9.5 The Position Object...... 70 9.6 Handling Errors...... 71 9.7 The PositionOptions Object...... 72 9.8 Browser Support...... 72 9.9 Quiz...... 72 9.10 Lab: Getting our location to display it on a map...... 73
10 HTML5 Web Workers 74 10.1 The Current JavaScript Execution Model...... 74 10.2 Introduction To Web Workers...... 74 10.3 Usage Of Web Workers...... 75 10.4 Communication APIs...... 75 10.5 Handling Errors...... 76 10.6 Browser Support...... 76 10.7 Quiz...... 76 10.8 Lab: Create and see a worker in action...... 76
11 HTML5 Messaging APIs 78 11.1 Understanding the same origin policy...... 78 11.2 Workaround to the same origin policy...... 79 11.3 Cross-document messaging...... 79 11.3.1 Sending a message...... 79 11.3.2 Receiving a message...... 80 11.3.3 Browser support...... 80 11.4 XMLHttpRequest Level 2...... 80 11.4.1 Making a request...... 80 11.4.2 Progress Event...... 81 11.4.3 Browser Support...... 82 Marakana HTML5 Training vii
12 Web Sockets 83 12.1 Overview Of The Current "Real-Time" Solutions...... 83 12.1.1 Polling Architecture...... 84 12.1.2 Long Polling Architecture...... 85 12.2 Overview Of Web Sockets API And Protocol...... 85 12.2.1 Web Sockets Handshake...... 85 12.2.2 The Web Sockets API...... 87 12.3 Advantages Of Web Sockets...... 88 12.4 Browser Support...... 88 Marakana HTML5 Training 1 / 89
Chapter 1
History, Vision And Future Of HTML5
1.1 What Is HTML5?
• Successor of HTML 4.01 and XHTML 1.1 • It comes with new tags, features and APIs • Below is a non exhaustive list of features that tend to be labelled as "HTML5" in the medias:
– New structural elements (
Note However, a precision needs to be given on that list: Some features were in the past in the same specification as the HTML5 specification but now have their own specification such as Web Sockets, some other features were never related to HTML5 such as Geolocation but all of these features in the end tends to be labelled "HTML5" since they are going to help us building great web applications!
• HTML5 brings also more clarification and standardizes many features that were used before by adding more documen- tation
1.2 History And Major Actors
HTML5 is not so new, it has a lot of background history. It almost happened that it could not exist. Major actors have been involved in its history with a lot of discussions, conflicts and different concerns. Marakana HTML5 Training 2 / 89
1.2.1 A Little Retrospective
• December 1997: HTML 4.0 is published by the W3C (recommendation) and the first HTML working group is closed
• February - March 1998: XML 1.0 is published (recommendation). Mozilla.org is launched • May 1998: A W3C workshop, "Shaping the Future of HTML", came out with the following conclusion:
In discussions, it was agreed that further extending HTML 4.0 would be difficult, as would converting 4.0 to be an XML application. The proposed way to break free of these restrictions is to make a fresh start with the next generation of HTML based upon a suite of XML tag-sets. — W3C Working Group http://www.w3.org/MarkUp/future/
• December 1999 - January 2000: ECMAScript 3rd Edition, XHTML 1.0 (Basically HTML tags reformulated in XML) and, HTML 4.01 recommendations are published • May 2001: XHTML 1.1 recommendation is published • August 2002: XHTML 2.0 first working draft is released. We clearly see that the main effort of the W3C so far aimed to have web pages strict and valid. Some web notable make a point on that, as Mark pilgrim says in its blog post:
. . . I’m building a parser that will be used in an end-user product, and end users don’t care about RSS or XML or XSLT or standards of any kind. Nor should they care, nor should they be required to care. Look at it this way: imagine you made a browser that only rendered sites authored in valid HTML or XHTML. How much of the web would your users be able to see? 1%? 0.1%? Less? . . . — Mark Pilgrim http://diveintomark.org/archives/2002/08/20/how_liberal_is_too_liberal
• December 2002: XHTML 2.0 second working draft published. Some web notables do not agree with the W3C, as Daniel Glazman wrote in a W3C mail list: http://lists.w3.org/Archives/Public/www-html/2003Jan/0125.html • June 2004: W3C workshop on "Web Applications and Compound Documents". Major web actors were present. Among them, the Mozilla Foundation and Opera Software gave their vision on how the future web should be (http://www.w3.org/- 2004/04/webapps-cdf-ws/papers/opera.html). Their proposition was voted down. This will lead to the creation of the WHAT Working Group.
• October 2006: Tim Berners-Lee, founder of the W3C, announce that the W3C will work with the WHAT Working Group together in order to evolve HTML:
Some things are clearer with hindsight of several years. It is necessary to evolve HTML incrementally. The attempt to get the world to switch to XML, including quotes around attribute values and slashes in empty tags and namespaces all at once didn’t work. . . The plan is to charter a completely new HTML group. Unlike the previous one, this one will be chartered to do incremental improvements to HTML, as also in parallel xHTML. — Tim Berners-Lee http://dig.csail.mit.edu/breadcrumbs/node/166
• January 2008: First W3C working draft of HTML5 is published!!
1.2.2 What Is The W3C?
• Stands for World Wide Web Consortium • Founded and lead by Tim Berners-Lee • Internationally main responsible of standards for the World Wide Web Marakana HTML5 Training 3 / 89
• Any W3C Document goes through the following maturity levels until becoming a recommendation:
– Working Draft (WD) – Last Call Working Draft – Candidate Recommendation (CR) – Proposed Recommendation (PR) – W3C Recommendation (REC)
1.2.3 What Is The WHATWG?
• Stands for Web Hypertext Application Technology Working Group • Founded in 2004 by individuals from Apple, The Mozilla Foundation, and Opera Software due to a concern about W3C vision of the web • Anyone can contribute for free: http://wiki.whatwg.org/wiki/What_you_can_do • Current editor is Ian Hickson (almost considered as the father of HTML5) • Until they joined their force with the W3C in 2006 they were the only one working on what we know as the HTML5 specification • Subscribe to the mailing list: It is a great way to learn, to contribute and be informed
1.3 Vision And Philosophy Behind HTML5
• The HTML Working Group has published a "HTML Design Principles" (http://www.w3.org/TR/html-design-principles/- ) • It applies to authors as well as implementors • Let us go through each of these principles
1.3.1 Compatibility
• Support existing content
– User-agents should be able to deal with old content containing deprecated tags and attributes
• Degrade gracefully
– For instance, there are ways to test if a HTML5 feature is available or not. If not, provide a fallback
• Do not reinvent the wheel
– When possible, use features that exist and work rather than spending time implementing new ones
• Pave the cowpaths • Evolution not revolution
– Old content should be able to use new features without the need to make unrelated changes Marakana HTML5 Training 4 / 89
1.3.2 Utility
• Solve real problems
– When possible, specifications must be aimed to solve existing problems that the web is facing
• Priority of constituencies
In case of conflict, consider users over authors over implementors over specifiers over theoretical purity. . . — http://www.w3.org/TR/html-design-principles/
• Secure by design
– New features should be secure. A good example of that is the concept of "same origin" that will be discussed later in this course
• Separation of concerns
– HTML should be used for structuring content. Use CSS to present the content
Note Here for example are some of the presentational tags that have been removed in HTML5 like ,
• DOM consistency
– The produced DOM tree of a web page should be the same on different browser. It is very important for scripts that work against the DOM tree
1.3.3 Interoperability
• Well-defined behavior
– Behavior of tags should be clearly defined in order to run the same way in different user-agents
• Avoid needless complexity
– Features should be as simple as possible, easy to be implemented and easy for web developers to understand.
• Handle errors
– We do not want end-users to be exposed to hard failure in case of errors from web developers. These web developers should prefer graceful error recovery to hard failure Marakana HTML5 Training 5 / 89
1.3.4 Universal Access
• Media independence
Features should, when possible, work across different platforms, devices, and media. — http://www.w3.org/TR/html-design-principles/
• Support world languages
– Authors should be able to publish their web site in any languages
• Accessibility
– Features should be designed in a accessible way to users with disabilities – For instance, blind users cannot see this is why there is the alt attribute that can be read by browser with assistive technology.
1.4 Future Of HTML5
• At the time of this writing, the current HTML5 Working Draft is from April 11th, 2011 • Candidate Recommendation is planned for 2012 while Proposed Recommendation is planned for 2022 • 2022?!? You might be asking yourself why will this take so long? or can I start using HTML5?
1.4.1 Timeline
• HTML 4 might have reached recommendation levels but:
– There is no real test suite – Some parts of the specification do not even have real implementation – Some parts of the specification are not fully documented – Big parts are not interoperable – Thousands of known errors have not been fixed
Note Nowadays, there are more expectations for a specification to become recommendation. So do not worry about 2022. Marakana HTML5 Training 6 / 89
Chapter 2
Getting Started With HTML5
2.1 The State Of Browser Support
• Most part of the specification is implemented in latest browsers
Note Among all latest browsers on the market, Internet Explorer is the one that support less HTML5 features. The next version, IE9, is supposed to support new tags, h.264 video, embedded audio, SVG and CSS3.
• Because of legacy browsers and also the fact that all latest browsers do not implement the same features and sometimes partially, you want to test features and provide alternatives
• There are some helpful websites that will help you to see which features are supported in which browser:
– http://www.caniuse.com/ provides a table comparison of major browsers for different features – http://www.html5test.com/ provides a HTML5 "score" with detail on what you can use or not
2.1.1 Browsers In Mobile Devices
• HTML5 has a lot of potential for creating mobile web applications. • Below are some of the key features that will be critical to web applications:
– Offline Support – Canvas and Video – GeoLocation API – Advanced Forms Marakana HTML5 Training 7 / 89
Figure 2.1: Different keyboards on iOS depending on input types
• Below are the pros and cons of using web apps rather than native apps:
Pros Cons
– Available on all platforms / connected devices – Lower usability due to UI design limitations – One single place to find the web app – Lower performance due to added browser layer – Low development cost / high ROI: – Harder to discover cool apps without store front / user reviews * Simpler language (HTML / JavaScript) – Limited HTML5-compliant browser support * Shorter / cheaper debugging process (depends on the smartphone) * Much larger potential reach – Low maintenance cost – Free from carrier / device manufacturer / approval control / revenue share – Users always have the latest app
Note Performance-critical apps will likely remain native.
• Most of the browsers on current mobiles are based on the webkit engine. However the version of this engine may differ from a mobile to another one
2.1.2 Feature Detection
• Since we cannot say a browser supports HTML5 but supports HTML5 features, we need to check if a feature is present when writing our web app Marakana HTML5 Training 8 / 89
• To detect if a browser supports a feature, you can use, depending on the feature to check, the following techniques:
– Check if a property exists on a global object. For instance to check if geolocation is supported: return!!navigator.geolocation;
– Dynamically create an element and then check if a property exists on this element. For instance, to check if your navigator supports canvas: return!!document.createElement(’canvas’).getContext;
– Another technique here mostly use for video (when checking if a codec is supported) consists in creating an element, check if a specific method exists on this element, call this same method and finally check the returned value. function isCodecSupported(codec){ if(!!document.createElement(’video’).canPlayType){ varv= document.createElement("video"); returnv.canPlayType(codec); } // Just means that video would not be supported return false; }
– Finally, the last technique is to create an element, set a property to a specific value and then check if the property has conserved the affected value. A concrete example will be discussed later when discussing HTML5 forms and new input types. function isInputTypeSupported(type){ vari= document.createElement("input"); i.setAttribute("type", type); returni.type !=="text"; }
• It also exist an open source and MIT-licensed JavaScript library to simplify all this detection work: Modernizr (http://www.modernizr.com). For instance, detecting if (for selecting date in HTML5 forms) exists with Modernizr: if(!Modernizr.inputtypes.date){ // is not supported in this browser // You can provide an alternative using jQueryUI or other JavaScriptUI frameworks ←- for instance }
2.2 Support For Legacy Browsers
• When checking if HTML5 features exist on a browser, you can provide alternatives if needed. • Some features just gracefully degrade, some other might need extra work. Marakana HTML5 Training 9 / 89
2.2.1 Graceful Degradation
• When talking about graceful degradation, we talk about features that, if not supported in a browser, will not break your web application. For instance:
– New input types that are not supported automatically fallback to – When the
2.2.2 Emulation
• Features that are not supported yet on browsers can be emulated so your applications are backward compatible • You can use polyfills to emulate features that are not supported
– Polyfills (also called shims) are pieces of code or plugins that emulate a non existing feature
• A non exhaustive list of these polyfills:
– Google Gears can emulate many features such as SQL Storage, Geolocation, Offline applications and Workers. – Usage of JavaScript libraries – Third party plugins such as Flash, Silverlight, etc. . . (mostly for audio/video content)
• A list of shims and polyfills has been created by the creators of Modernizr: http://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
2.3 Developer Tools
• Now you are ready to dive in HTML5, let us talk about what compose an HTML5 web application and what are the tools available to code and debug? • First thing first, an HTML5 web application is composed of the following: HTML, CSS, JavaScript, some images and sometimes manifest files (for offline caching purpose. This will be discussed in the Offline Application chapter). • Any classic text editor will do the job when developing web applications. However using IDE or advanced text editor can save you a lot of time (code completion, snippets, etc. . . ).
Note As far as the specification is becoming more and more stable, IDE support will evolve. Nonetheless, some support already exist: WebStorm 2.0 from JetBrains, Netbeans IDE 6.9, Adobe Dreamweaver CS5.5, Komodo Edit 6, Aptana Studio 3.0.0 Beta (also exist as an Eclipse plug-in), etc. . .
• Along with these authoring tools, you can take advantage of browsers development tools such as Chrome developer console, Safari web inspector, Opera dragonfly and Firebug plugin for Firefox for live coding and debugging purposes. Marakana HTML5 Training 10 / 89
2.4 Quiz
1. Cite 3 advantages that web apps have on native apps 2. The Modernizr library can help to detect if HTML5 is supported in your browser:
• True • False
3. What are the assets composing an HTML5 web application? 4. What are the tools required to build an HTML5 web application? Marakana HTML5 Training 11 / 89
Chapter 3
Structure Of A Web Page
• Before starting to talk about different HTML5 features, let us start with the basics. • In this chapter we are going to discuss:
– How HTML5 pages are written? – What has changed compared to HTML4? – What are the new tags and the new attributes?
3.1 HTML5 DOCTYPE
• The release of IE5 on Mac lead to a major problem
– Many web content based on bad authoring no longer rendered on IE5 for Mac since this browser respected the standards so much – Microsoft later decided to introduce this DOCTYPE declaration to let web developers choose how the web page should be rendered (by activating a certain browser mode: quirks and standards modes) – Pages with no DOCTYPE used to be rendered the same way as before (quirks mode)
• An HTML page first starts with the DOCTYPE declaration
– This declaration needs to be the very first line that you should find in a HTML page (even a blank line before can prevent it to work)
• There is only one DOCTYPE in HTML5:
– This triggers the standard mode in a browser – Only 15 characters, which is way easier than writing something like this: Marakana HTML5 Training 12 / 89
3.2 Page Encoding
• Is the mapping between what you can see on the browser and what is stored in the disk (from 0 and 1 to real characters) • Character encoding can be specified in two places:
– At server level on the HTTP headers – In the
element of a web page using the tagNote Character encoding declared in the
using the tag takes precedence over the one declared at server level• Not specifying a character encoding can lead to serious security issues: http://code.google.com/p/doctype/wiki/ArticleUtf7 • There is now a short way to declare character encoding: ...
... ... ...Note Character encoding must be specified in the first 512 bytes of the document
3.3 HTML5 Markup
• Among all HTML5 features, improving the language itself was the top motivation to create HTML5 • HTML today:
– HTML has structural AND presentational tags. HTML should only care about structure and not presentation
Note There are also attributes that have to do with presentation as well. We will later see what does the HTML5 specifi- cation recommends about that.
– As it is today, HTML semantics are fixed not extensible * Overuse of id and class attributes ⇒ Pseudo-semantic markup
Note For instance, writing
• Overall, the goal of HTML5 is to reflect the web as it is used nowadays Marakana HTML5 Training 13 / 89
3.3.1 New And Updated Elements
• HTML5 introduces 28 new elements:
3.3.2 Structural Elements
• We previously discussed that there is currently an overuse of id or class attributes combined with the