Upgrade to Pro — share decks privately, control downloads, hide ads and more …

HTML5 (Part 1)

djsipe
March 13, 2012

HTML5 (Part 1)

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.

djsipe

March 13, 2012
Tweet

More Decks by djsipe

Other Decks in Technology

Transcript

  1. HTML HTML5 5 HTML HTML5 5 is a collection of

    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.
  2. HTML5 HTML5 Today, we’re going to talk about two areas:

    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
  3. Online/Offline Detection Online/Offline Detection and Storage and Storage HTML5 provides

    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)
  4. Detect Internet Connection Detect Internet Connection HTML5 allows you to

    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
  5. Detect Internet Connection Detect Internet Connection Detecting Online vs. Offline:

    Detecting Online vs. Offline: if ( if (navigator.onLine navigator.onLine) { ) { alert(“We’re online!”); alert(“We’re online!”); alert(“We’re online!”); alert(“We’re online!”); } } else { else { alert(“We’re offline”); alert(“We’re offline”); } }
  6. Detect Internet Connection Detect Internet Connection Detecting Online vs. Offline

    via a browser Detecting Online vs. Offline via a browser e event: vent: function function detectStatus detectStatus() { () { if if ( (navigator.onLine navigator.onLine) { ) { if if ( (navigator.onLine navigator.onLine) { ) { alert alert(“We’re online!”); (“We’re online!”); } } else else { { alert alert(“We’re offline”); (“We’re offline”); } } } } addEvent addEvent(window, ‘online’, (window, ‘online’, detectStatus detectStatus); ); addEvent addEvent(window, ‘offline’, (window, ‘offline’, detectStatus detectStatus); ); See: See: http://html5demos.com/offline
  7. Offline Storage Offline Storage Before HTML5, we had to rely

    on... Before HTML5, we had to rely on... Cookies Cookies Third Third- -Party Applications Party Applications
  8. Offline Storage Offline Storage But now, with HTML5, there are

    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
  9. Web Storage Web Storage Web Storage allows you to store

    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
  10. Web Storage Web Storage localStorage localStorage window.localStorage window.localStorage['username'] = "Fred";

    ['username'] = "Fred"; sessionStorage sessionStorage if ( ! if ( !sessionStorage sessionStorage['counter ['counter'] ) { '] ) { sessionStorage sessionStorage['counter'] = 0 ['counter'] = 0; ; } } else { else { sessionStorage sessionStorage['counter ['counter']++; ']++; } }
  11. Web Storage Web Storage At present, only basic data types

    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); );
  12. Strengths Weaknesses 1. Supported on all modern browsers, including iOS

    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.
  13. Web SQL Database Web SQL Database This feature of HTML5

    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.”
  14. Web SQL Database Web SQL Database var var db =

    db = window.openDatabase window.openDatabase( ( ' 'MyDB MyDB', // ', // dbName dbName '1.0 '1.0', // version ', // version 'test 'test database', // description database', // description 2 2 * 1024 * 1024, // * 1024 * 1024, // estimatedSize estimatedSize in bytes in bytes function(db function(db) {} // optional ) {} // optional creationCallback creationCallback ); ); var var scoresEl scoresEl = = document.getElementById document.getElementById('results ('results'); '); var var scoresEl scoresEl = = document.getElementById document.getElementById('results ('results'); '); scoresEl.innerHTML scoresEl.innerHTML = 'Scores: = 'Scores: '; '; db.transaction db.transaction( function( ( function(tx tx) { ) { tx.executeSql tx.executeSql("SELECT * FROM ("SELECT * FROM Scores Scores" ", [], function( , [], function(tx tx, result) { , result) { for for ( (var var i i=0 =0, , item=null item=null; ; i i < < result.rows.length result.rows.length; ; i i++) { ++) { item item = = result.rows.item result.rows.item( (i i); ); scoresEl.innerHTML scoresEl.innerHTML += item += item['Score ['Score'] + ", "; '] + ", "; } } } } ); ); }); });
  15. Strengths Weaknesses 1. Supported on major mobile browsers as well

    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.
  16. IndexedDB IndexedDB IndexedDB IndexedDB is a good compromise between is

    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.
  17. IndexedDB IndexedDB Step 1: Open the Database & Create an

    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} ); ); }; }; } }
  18. IndexedDB IndexedDB Step Step 2 2: Add Some Data :

    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);}; );};
  19. Strengths Weaknesses 1. Asynchronous API offering good UI performance. 2.

    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.)
  20. New Form Elements New Form Elements HTML HTML5 5 features

    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.
  21. New Input Types New Input Types HTML5 features a slew

    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)
  22. New Input Types New Input Types These new input types

    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.
  23. New Input Attributes New Input Attributes Attribute Attribute Attribute Attribute

    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
  24. Form Validation Form Validation HTML HTML5 5 offers form validation

    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]).*" /> " />
  25. Form Validation Form Validation When a user tries to submit

    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
  26. Further Reading Further Reading Lots of great articles and demos

    • 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