First of a series of presentations on HTML5. This presentation covers online/offline detection, persistent data APIs, and some of the new HTML form features of HTML5.
features, is a collection of features, technologies, technologies, and APIs and APIs that brings the that brings the power of the desktop and the vibrancy of power of the desktop and the vibrancy of multimedia experience to the multimedia experience to the web. web. multimedia experience to the multimedia experience to the web. web. It includes It includes the the 5 5th th revision revision of the HTML of the HTML markup language, CSS markup language, CSS3 3, and a series of , and a series of JavaScript APIs. JavaScript APIs.
Today, we’re going to talk about two areas: Online/Offline Detection Online/Offline Detection and Storage and Storage Semantics: Semantics: HTML Forms HTML Forms
new tools for crafting HTML5 provides new tools for crafting websites that can: websites that can: • • Detect an internet connection Detect an internet connection • • Detect an internet connection Detect an internet connection • • Store data locally within the Store data locally within the browser (no not just cookies) browser (no not just cookies)
create offline HTML5 allows you to create offline- -online online aware applications. aware applications. Users can interact with cached data until an Users can interact with cached data until an Users can interact with cached data until an Users can interact with cached data until an Internet connection is detected. Internet connection is detected. Example: Example: Mobile Mobile
a few more But now, with HTML5, there are a few more options: options: • • Web Storage Web Storage • • Web Storage Web Storage • • Web SQL Database Web SQL Database • • IndexedDB IndexedDB
and retrieve data as Web Storage allows you to store and retrieve data as if you were using properties from a variable.* if you were using properties from a variable.* Two web storage APIs are available: Two web storage APIs are available: localStorage localStorage Data saved to Data saved to localStorage localStorage will be available even will be available even after the user closes their web browser. after the user closes their web browser. sessionStorage sessionStorage Data saved to Data saved to sessionStorage sessionStorage will be will be lost once the user closes their tab. lost once the user closes their tab. * Sort of
are supported At present, only basic data types are supported by all browsers for Web Storage. by all browsers for Web Storage. To store structured Objects you will need to To store structured Objects you will need to “serialize” & “ “serialize” & “deserialize deserialize” your data. ” your data. To store structured Objects you will need to To store structured Objects you will need to “serialize” & “ “serialize” & “deserialize deserialize” your data. ” your data. // Open game data, update high score and save again // Open game data, update high score and save again var var gameData gameData = = JSON.parse JSON.parse( (localStorage localStorage[" ["savedGameData savedGameData"]); "]); gameData.highScore gameData.highScore = = 5000 5000; ; localStorage localStorage[" ["savedGameData savedGameData"] = "] = JSON.stringify JSON.stringify( (gameData gameData); );
and Android, for several years (IE since version 8). 1. Poor performance when searching large/complex data, due to lack of indexing. 2. Deserializing data degrades Web Storage Web Storage 2. Relatively simple to use. 3. Synchronous API means simpler code. 4. Semantic events available to keep other tabs/windows in sync. 2. Deserializing data degrades performance for large/complex datasets. 3. Need to ensure data consistency and integrity, since data is effectively unstructured.
allows you to create and This feature of HTML5 allows you to create and use local use local SQLite SQLite databases to power your databases to power your applications. applications. Now you have indexes, tables, joins and all the Now you have indexes, tables, joins and all the Now you have indexes, tables, joins and all the Now you have indexes, tables, joins and all the warm fuzzy feelings that come with a warm fuzzy feelings that come with a relational database. relational database. But beware...“With great power But beware...“With great power comes great complexity.” comes great complexity.”
as several desktop browsers. 2. Asynchronous, giving good performance generally. 1. Deprecated. Will not be supported on IE or Firefox, and will probably be phased out from the other browsers at some stage. Web SQL Database Web SQL Database performance generally. 3. Good search performance, since data can be indexed according to search keys. 4. Robust, since it supports a transactional database model. 5. Easier to maintain integrity of data, due to rigid data structure. some stage. 2. Steep learning curve, requiring knowledge of relational databases and SQL. 3. Diminishes agility: schema must be defined upfront and all records must match table structure.
a good compromise between the un the un- -indexed indexed Web Storage Web Storage and the and the somewhat cumbersome somewhat cumbersome Web SQL Web SQL Database Database.. Database Database.. It provides a relatively simple It provides a relatively simple NOSQL API for storing data. NOSQL API for storing data.
Object Store Step 1: Open the Database & Create an Object Store var var db = db = window.indexedDB.open window.indexedDB.open(' ('FriendDB FriendDB', 'My Friends ', 'My Friends!'); !'); if if ( (db.version db.version != '1') { != '1') { var var setVrequest setVrequest = = db.setVersion db.setVersion(v); (v); setVrequest.onfailure setVrequest.onfailure = = function(){/* handle error */}; function(){/* handle error */}; setVrequest.onfailure setVrequest.onfailure = = function(){/* handle error */}; function(){/* handle error */}; // // onsuccess onsuccess is the only place we can create Object Stores is the only place we can create Object Stores setVrequest.onsuccess setVrequest.onsuccess = function(e) { = function(e) { var var store = store = db.createObjectStore db.createObjectStore( ( "Friends“, "Friends“, { {keyPath keyPath: : "id“, "id“, autoInrement autoInrement: true} : true} ); ); }; }; } }
Add Some Data var var trans = trans = db.transaction db.transaction( ↓ ( ↓ [" ["Friends"], Friends"], IDBTransaction.READ_WRITE IDBTransaction.READ_WRITE, , 0 0); ); var var store = store = trans.objectStore trans.objectStore("Friends"); ("Friends"); var var store = store = trans.objectStore trans.objectStore("Friends"); ("Friends"); var var request = request = store.put store.put({ ({ name name: 'DJ', : 'DJ', gender gender: 'male', : 'male', likes likes: 'html : 'html5 5' ' }); }); request.onsuccess request.onsuccess = function(e) {/* Do something */}; = function(e) {/* Do something */}; request.onerror request.onerror = = function(e) {console.log( function(e) {console.log(e.value e.value);}; );};
Good search performance, since data can be indexed according to search keys. 1. Somewhat complex API. 2. Need to ensure data consistency and integrity, since data is effectively unstructured. (This is the standard flipside IndexedDB IndexedDB according to search keys. 3. Supports agile development, with flexible data structures. 4. Robust, since it supports a transactional database model. 5. Fairly easy learning curve, due to a simple data model. 6. Decent browser support: Chrome, Firefox, mobile FF, IE10. (This is the standard flipside weakness to the typical strengths of NOSQL structures.)
five new form features five new form fields̶ fields̶however however, browser , browser support for these elements vary. support for these elements vary. New Field New Field New Field New Field Description Description Description Description Example Example Example Example progress Represents completion of a task. Progress bar meter Represents a scalar measurement within a known Gauge, meter Represents a scalar measurement within a known range. Gauge, thermometer datalist Represents a set of option elements that can be used in combination with the new list attribute for input to make dropdown menus. Auto-complete drop-downs keygen A control for key-pair generation. (When the form is submitted, the private key gets stored in the local keystore, and the public key is sent to the server.) Password field following the SSL model of public/private keys output Display the result of a calculation Element showing the sum of 2 other fields.
of new <input> types. These HTML5 features a slew of new <input> types. These default back to “text” if the browser doesn’t support it. default back to “text” if the browser doesn’t support it. Name Name Name Name Description Description Description Description Name Name Name Name Description Description Description Description tel A formatted phone number. month A month search Similar to a text field except week A week search Similar to a text field except for visual styling. week A week url A single absolute URI time A time of day email One or more email addresses datetime-local A date and time (user’s timezone) datetime A date and time (UTC timezone) number Numeric input date A date range A numeric value between a min/max value (slider) Color Lowe-rcase color code (#ffffff)
are also helpful for These new input types are also helpful for displaying validation feedback to the user. displaying validation feedback to the user. For example, if a user enters “ For example, if a user enters “abc abc” in a “number” ” in a “number” For example, if a user enters “ For example, if a user enters “abc abc” in a “number” ” in a “number” input field the CSS3 pseudo input field the CSS3 pseudo- -class class :invalid :invalid is is automatically applied to the element. automatically applied to the element. This allows you to create a This allows you to create a stylesheet stylesheet that automatically highlights bad that automatically highlights bad user input. user input.
Description Description Description Description Attribute Attribute Attribute Attribute Description Description Description Description autofocus “focuses” element when page is loaded placeholder Displays light help text inside the element HTML5 also offers a number of new attributes for HTML5 also offers a number of new attributes for forms. Below is a sampling: forms. Below is a sampling: page is loaded inside the element until the user starts typing form Allows inputs to be located outside a <form> tag required Flags an input as required for browser- based validation pattern Validates user input against a regular expression novalidate Disables validation when on a <form> element
out of the box that is offers form validation out of the box that is built right into the browser. built right into the browser. Using attributes like Using attributes like pattern pattern, you can define , you can define Using attributes like Using attributes like pattern pattern, you can define , you can define complex regular expressions that users’ input is complex regular expressions that users’ input is validated against. validated against. <! <!-- -- Required password Required password field field requiring a minimum requiring a minimum 8 8 characters characters, , one number, one uppercase and one lowercase one number, one uppercase and one lowercase letter letter -- --> > <input <input name="password" type="password" name="password" type="password" required required pattern pattern="(?=^.{ ="(?=^.{8 8,}$)((?=.* ,}$)((?=.*\ \d)|(?=.* d)|(?=.*\ \W+))(?![. W+))(?![.\ \n])(?=.*[A n])(?=.*[A- -Z Z])(?=.*[ ])(?=.*[a a- -z]).* z]).*" /> " />
a form where the built When a user tries to submit a form where the built in validation fails, they will automatically see in validation fails, they will automatically see messages like these: messages like these: Chrome Chrome Chrome Chrome Opera Opera Firefox Firefox
• html5rocks.com Good article covering HTML5 validation in depth • alistapart.com/articles/forward-thinking-form-validation/ • alistapart.com/articles/forward-thinking-form-validation/ Good presentation slides for HTML storage (slightly outdated) Good presentation slides for HTML storage (slightly outdated) • • html5 html5- -demos.appspot.com/static/html5storage/index.html demos.appspot.com/static/html5storage/index.html Great HTML5 toolset full of best practices Great HTML5 toolset full of best practices • • html5boilerplate.com html5boilerplate.com