Tuesday, November 2, 2010   1
HTML5: Building For a Faster Web           Performance       Features     Tools           Eric Bidelman - Google          ...
Agenda             • Performance        Wins                  • Web     Storage APIs                  • Web     Workers & ...
Eric Bidelman (@ebidel)             • University     of Michigan, BSE Computer &                  Electrical Engineering  ...
Performance             5                            @googledevlatam #devfest10Tuesday, November 2, 2010                  ...
Don’t Underestimate CSS3!             •    Rounded corners, box shadows, reflection, rotations, alpha, css masks           ...
Go Native!             • Use          native methods ( not libraries )                            JSON.parse();         JS...
Go Native!             <div id="main" class="shadow rounded"></div>      var cl = document.querySelector(#main).classList;...
JavaScript 1.6                •   Array iterative methods: map(), filter(), forEach(),                    every(), some() ...
HTML5 Markup                               ( for web apps )             10                            @googledevlatam #dev...
REL Attributes             rel=”pingback”             •    enables reverse linking             •    automatically notify o...
REL Attributes             rel=”pingback”             •    enables reverse linking             •    automatically notify o...
REL Attributes             rel=”pingback”             •    enables reverse linking             •    automatically notify o...
Data Attributes           <output id="out" data-id="good" data-name="joe"                   data-screen-name="user1"></out...
HTML5 Forms             •    New <input> types: tel,                  email, url, datetime, date,                  month, ...
Demos                                      open             14                            @googledevlatam #devfest10Tuesda...
Web Storage                              not just for offline             15                            @googledevlatam #d...
Web Storage APIs                  localStorage                  •    key/value pairs                  •    great for stori...
var webdb = {};     webdb.open = function() {       webdb.db = openDatabase(Todo, 1.0, todo-manager, 5*1024*1024); //5MB  ...
4th Storage Option...                  Indexed DB                  •    Hybrid of localStorage/sessionStorage APIs        ...
Application Cache             •    Caches entire web app locally             •    Server with mime-type: text/cache-manife...
Cache Manifest File                        <html manifest="example.manifest">... </html>                        CACHE MANI...
JavaScript API                            var appCache = window.applicationCache;         if (appCache.status == window.ap...
Debugging App Cache                            about:appcache-internals           22                                @googl...
Demo                                http://3.ly/timer             23                            @googledevlatam #devfest10...
Dedicated Workers: Getting Stuff Done             •    Take advantage of multi-core CPUs             •    Use cases:      ...
JavaScript API         <output id="result"></output>         <script>           var worker = new Worker(task.js);         ...
Inline Workers      <!DOCTYPE html>      <html>      <body>        <script id="worker1" type="text/html">          onmessa...
WebSockets: Realtime             •    Bi-directional communication                  •    Eliminates need for XHR polling! ...
Javascript API      var ws = new WebSocket("ws://www.example.com/path");      ws.onopen = function () { // connection esta...
Demo                            http://mrdoob.com/projects/multiuserpad/             29                                   ...
Server-Sent Events: Notifications             • Server         initiated pushes             • mimetype:             text/e...
SSE: Client Code           var source = new EventSource(events.php);           source.onmessage = function(event) {       ...
SSE: Server Code           <?php           header(Content-Type: text/event-stream);           function sendMsg($id , $msg)...
Demo                                      open             33                            @googledevlatam #devfest10Tuesday...
Tools & Compatibility             34                                @googledevlatam #devfest10Tuesday, November 2, 2010   ...
Chrome Developer Tools             35                                 @googledevlatam #devfest10Tuesday, November 2, 2010 ...
Google Fonts API                            code.google.com/apis/webfonts/           36                                  @...
37                            @googledevlatam #devfest10Tuesday, November 2, 2010                                37
37                            @googledevlatam #devfest10Tuesday, November 2, 2010                                37
Google Fonts API     <!DOCTYPE html>     <html>       <head>         <link rel="stylesheet" type="text/css"            hre...
Google Fonts API     <!DOCTYPE html>     <html>       <head>         <link rel="stylesheet" type="text/css"            hre...
Demo                            www.gobiernodechile.cl             39                            @googledevlatam #devfest1...
HTML5Rocks.com             1.Step-by-Step Tutorials             2.Code Playground             3.Interactive Presentation  ...
Is HTML5 Ready?             41                             @googledevlatam #devfest10Tuesday, November 2, 2010            ...
Text                            caniuse.com                                 42       Google Developer Day 2010Tuesday, Nov...
Modernizr Library          •     BAD: checking navigator.userAgent                •   Unreliable - users change this!     ...
Usage                            <div id="audio">                              <audio>                                <sou...
Google Chrome Frame             1.Add a single meta tag to your site                  • if      !installed: direct users t...
Thanks!             •    Tools                  •    Google Fonts API: code.google.com/apis/webfonts/                  •  ...
Questions?                            Stay up to date: @googledevbr             47                                  @googl...
Tuesday, November 2, 2010   48
Upcoming SlideShare
Loading in...5
×

HTML5: Building for a Faster Web

7,031

Published on

HTML5. Covers: workers, websockets, SSEs, storage, js improvements, tips, tricks, tools.

Published in: Technology, Design
0 Comments
23 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
7,031
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
23
Embeds 0
No embeds

No notes for slide

HTML5: Building for a Faster Web

  1. 1. Tuesday, November 2, 2010 1
  2. 2. HTML5: Building For a Faster Web Performance Features Tools Eric Bidelman - Google Google DevFest - Buenos Aires, Argentina Nov 2, 2010Tuesday, November 2, 2010 2
  3. 3. Agenda • Performance Wins • Web Storage APIs • Web Workers & Web Sockets • Tools & Resources • Compatibility 3 @googledevlatam #devfest10Tuesday, November 2, 2010 3
  4. 4. Eric Bidelman (@ebidel) • University of Michigan, BSE Computer & Electrical Engineering • Developer Programs Engineer, Google • Docs / Sites / Health / Base / OAuth / Chrome / HTML5 4 @googledevlatam #devfest10Tuesday, November 2, 2010 4
  5. 5. Performance 5 @googledevlatam #devfest10Tuesday, November 2, 2010 5
  6. 6. Don’t Underestimate CSS3! • Rounded corners, box shadows, reflection, rotations, alpha, css masks • CSS animations & transitions div.box {   left: 40px;     -webkit-transition: left 0.3s ease-out;      -moz-transition: left 0.3s ease-out;          -o-transition: left 0.3s ease-out;   } div.box.totheleft { left: 0px; } div.box.totheright { left: 80px; } • 3D transforms trigger HW compositing in the GPU -webkit-transform: translate3d(10px, 0, 0); • pseudo-selectors are your friend ( :hover, :active, :valid, :invalid, :focus, :empty ) • Web Fonts 6 @googledevlatam #devfest10Tuesday, November 2, 2010 6
  7. 7. Go Native! • Use native methods ( not libraries ) JSON.parse(); JSON.stringify(); ‘ too much padding ‘.trim(); • Query, don’t walk the DOM! document.querySelector(‘#links’); document.querySelectorAll(‘.myclass > span’); • Data URIs: Render, don’t download canvas.toDataURL(); 7 @googledevlatam #devfest10Tuesday, November 2, 2010 7
  8. 8. Go Native! <div id="main" class="shadow rounded"></div> var cl = document.querySelector(#main).classList; for(var i = 0, c; c = cl[i]; ++i) { console.log(c); } cl.add(highlight); cl.remove(shadow); cl.toggle(highlight); cl.contains(shadow) == false // cl.toString() == el.className 8 @googledevlatam #devfest10Tuesday, November 2, 2010 8
  9. 9. JavaScript 1.6 • Array iterative methods: map(), filter(), forEach(), every(), some() [5,6,7,8].map(function(value){ // [50,60,70,80] return value * 10; }); // Return a new array of all mathematical constants under 2 [3.14, 2.718, 1.618].filter(function(number){   return number < 2; }); // [1.618] [html5,css3,webgl].forEach(function(value){ // use value }); • Array item location methods: indexOf(‘html5’), lastIndexOf(‘webgl’) 9 @googledevlatam #devfest10Tuesday, November 2, 2010 9
  10. 10. HTML5 Markup ( for web apps ) 10 @googledevlatam #devfest10Tuesday, November 2, 2010 10
  11. 11. REL Attributes rel=”pingback” • enables reverse linking • automatically notify original blog when sites link to it rel=”prefetch” • hint for the browser that the resource is likely to be used 11 @googledevlatam #devfest10Tuesday, November 2, 2010 11
  12. 12. REL Attributes rel=”pingback” • enables reverse linking • automatically notify original blog when sites link to it <a rel="pingback" href="http://blog.blogspot.com">A Blog</a> rel=”prefetch” • hint for the browser that the resource is likely to be used 11 @googledevlatam #devfest10Tuesday, November 2, 2010 11
  13. 13. REL Attributes rel=”pingback” • enables reverse linking • automatically notify original blog when sites link to it <a rel="pingback" href="http://blog.blogspot.com">A Blog</a> rel=”prefetch” • hint for the browser that the resource is likely to be used <a rel=”prefetch” href=”nextPage.html”>Next page &gt;</a> 11 @googledevlatam #devfest10Tuesday, November 2, 2010 11
  14. 14. Data Attributes <output id="out" data-id="good" data-name="joe" data-screen-name="user1"></output> var a = [], el = document.querySelector(#out); el.setAttribute(data-foo, bar); for (var key in el.dataset) { a.push(<b>, key, </b>: , el.dataset[key], <br/>); } el.innerHTML += a.join(); id: good name: joe screenName: user1 foo: bar 12 @googledevlatam #devfest10Tuesday, November 2, 2010 12
  15. 15. HTML5 Forms • New <input> types: tel, email, url, datetime, date, month, week, time, datetime-local, number, range, color • New attributes: placeholder, required, autofocus, pattern, min, max, step, speech, multiple, directory • ....you don’t need JS libraries! 13 @googledevlatam #devfest10Tuesday, November 2, 2010 13
  16. 16. Demos open 14 @googledevlatam #devfest10Tuesday, November 2, 2010 14
  17. 17. Web Storage not just for offline 15 @googledevlatam #devfest10Tuesday, November 2, 2010 15
  18. 18. Web Storage APIs localStorage • key/value pairs • great for storing user preferences localStorage.dateOfBirth = ‘1984-07-22’; delete localStorage.dateOfBirth; localStorage[‘user’] = JSON.stringify({username: john, id: 100}); var retrieved = JSON.parse(localStorage[‘user’]); sessionStorage • non-persistent key/value pairs (e.g. sensitive data) Web SQL DB • 5MB of persistent storage • reduces round trips to the server 16 @googledevlatam #devfest10Tuesday, November 2, 2010 16
  19. 19. var webdb = {}; webdb.open = function() {   webdb.db = openDatabase(Todo, 1.0, todo-manager, 5*1024*1024); //5MB }; webdb.onError = function(tx, e) { alert(Error + e.message); }; webdb.onSuccess = function(tx, r) {   // re-render all the data in the DOM. }; webdb.createTable = function() {   webdb.db.transaction(function(tx) {     tx.executeSql(CREATE TABLE IF NOT EXISTS +     todo(ID INTEGER PRIMARY KEY ASC, todo TEXT, added_on DATETIME), []);   }); }; webdb.addTodo = function(todoText) { webdb.db.transaction(function(tx){     var addedOn = new Date();     tx.executeSql(INSERT INTO todo(todo, added_on) VALUES (?,?),         [todoText, addedOn], webdb.onSuccess, webdb.onError);     }); }; 17 @googledevlatam #devfest10Tuesday, November 2, 2010 17
  20. 20. 4th Storage Option... Indexed DB • Hybrid of localStorage/sessionStorage APIs and Web SQL DB. • In-order retrieval • Faster search - Index on any keys • Browser support is still sparse • Implemented in FF4 • Recently landed in Chromium: webkitIndexedDB 18 @googledevlatam #devfest10Tuesday, November 2, 2010 18
  21. 21. Application Cache • Caches entire web app locally • Server with mime-type: text/cache-manifest • Why? 1.HTML, CSS, and JS stay fairly consistent 2.Native browser caching is unreliable 3.Caching resources creates speedier apps • Native iPhone & Android Gmail app uses AppCache 19 @googledevlatam #devfest10Tuesday, November 2, 2010 19
  22. 22. Cache Manifest File <html manifest="example.manifest">... </html> CACHE MANIFEST # 2010-08-10-v0.0.1 # Explicitly cached entries CACHE: index.html stylesheet.css images/logo.png scripts/main.js # static.html will be served if the user is offline FALLBACK: / /static.html # Resources that require the user to be online. NETWORK: * # login.php # http://api.twitter.com 20 @googledevlatam #devfest10Tuesday, November 2, 2010 20
  23. 23. JavaScript API var appCache = window.applicationCache; if (appCache.status == window.applicationCache.UPDATEREADY) {   appCache.swapCache();  // Fetch was successful, swap the new cache. } appCache.addEventListener(cached, handleCacheEvent, false); appCache.addEventListener(checking, handleCacheEvent, false); appCache.addEventListener(downloading, handleCacheEvent, false); appCache.addEventListener(error, handleCacheError, false); appCache.addEventListener(noupdate, handleCacheEvent, false); appCache.addEventListener(obsolete, handleCacheEvent, false); appCache.addEventListener(progress, handleCacheEvent, false); appCache.addEventListener(updateready, handleCacheEvent, false); 21 @googledevlatam #devfest10Tuesday, November 2, 2010 21
  24. 24. Debugging App Cache about:appcache-internals 22 @googledevlatam #devfest10Tuesday, November 2, 2010 22
  25. 25. Demo http://3.ly/timer 23 @googledevlatam #devfest10Tuesday, November 2, 2010 23
  26. 26. Dedicated Workers: Getting Stuff Done • Take advantage of multi-core CPUs • Use cases: • Text formatting of a long document • Syntax highlighting • Audio synthesis • Image processing • Processing large arrays or other computational tasks 24 @googledevlatam #devfest10Tuesday, November 2, 2010 24
  27. 27. JavaScript API <output id="result"></output> <script>   var worker = new Worker(task.js);   worker.onmessage = function(e) {     document.querySelector(result).textContent = JSON.stringify(e.data);   }; worker.postMessage(’start’); </script> importScripts(script1.js, ‘script2.js’); self.addEventListener(message, function(e) {   switch (e.data) {     case start:       self.postMessage({id: 12345, txt: Hi});       break;     case stop:       self.close(); // Terminates the worker.   }; }, false); 25 @googledevlatam #devfest10Tuesday, November 2, 2010 25
  28. 28. Inline Workers <!DOCTYPE html> <html> <body>   <script id="worker1" type="text/html">     onmessage = function(e) {     ...     };   </script>   <script>     var bb = new BlobBuilder();     bb.append(document.querySelector(#worker1).textContent);     var worker = new Worker(window.createObjectURL(bb.getBlob()));     worker.onmessage = function(e) {      ... };     worker.postMessage(); // Start the worker.   </script> </body> </html> 26 @googledevlatam #devfest10Tuesday, November 2, 2010 26
  29. 29. WebSockets: Realtime • Bi-directional communication • Eliminates need for XHR polling! • Close as we can get to TCP/IP socket connections in JS • Port 80 - ws:// Port 443 - wss:// • Use cases: • chat rooms • white boarding • games 27 @googledevlatam #devfest10Tuesday, November 2, 2010 27
  30. 30. Javascript API var ws = new WebSocket("ws://www.example.com/path"); ws.onopen = function () { // connection established ws.send("Hello, WebSocket"); }; ws.onmessage = function(evt) { alert(evt.data); ws.close(); }; ws.onclose = function () { // connection closed }; 28 @googledevlatam #devfest10Tuesday, November 2, 2010 28
  31. 31. Demo http://mrdoob.com/projects/multiuserpad/ 29 @googledevlatam #devfest10Tuesday, November 2, 2010 29
  32. 32. Server-Sent Events: Notifications • Server initiated pushes • mimetype: text/event-stream • Use cases: • Stock tickers • News tickers • Status update streams 30 @googledevlatam #devfest10Tuesday, November 2, 2010 30
  33. 33. SSE: Client Code var source = new EventSource(events.php); source.onmessage = function(event) { console.log(lastEventId: + event.lastEventId + , + event.data); }; source.onopen = function(event) { console.log(= Connection was opened); updateConnectionStatus(Connected, true); }; source.onerror = function(event) { if (event.eventPhase == EventSource.CLOSED) { console.log(= Connection was closed); updateConnectionStatus(Disconnected, false); } }; 31 @googledevlatam #devfest10Tuesday, November 2, 2010 31
  34. 34. SSE: Server Code <?php header(Content-Type: text/event-stream); function sendMsg($id , $msg) { echo "id: $id" . PHP_EOL; echo "data: $msg" . PHP_EOL; echo PHP_EOL; flush(); } $startedAt = time(); do { if ((time() - $startedAt) > 20) { // Limit connections to 20s. die(); } sleep(3); // Send message every 3s. sendMsg($startedAt , server time: . date("h:i:s", time())); } while(true); // Keep the connection open and only make one request. ?> 32 @googledevlatam #devfest10Tuesday, November 2, 2010 32
  35. 35. Demo open 33 @googledevlatam #devfest10Tuesday, November 2, 2010 33
  36. 36. Tools & Compatibility 34 @googledevlatam #devfest10Tuesday, November 2, 2010 34
  37. 37. Chrome Developer Tools 35 @googledevlatam #devfest10Tuesday, November 2, 2010 35
  38. 38. Google Fonts API code.google.com/apis/webfonts/ 36 @googledevlatam #devfest10Tuesday, November 2, 2010 36
  39. 39. 37 @googledevlatam #devfest10Tuesday, November 2, 2010 37
  40. 40. 37 @googledevlatam #devfest10Tuesday, November 2, 2010 37
  41. 41. Google Fonts API <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine|Inconsolata"/> <style> h1 { font-family: Tangerine, serif; font-size: 48px; text-shadow: 4px 4px 4px #aaa; } </style> </head> <body> <h1>Making the Web Beautiful!</h1> </body> </html> 38 @googledevlatam #devfest10Tuesday, November 2, 2010 38
  42. 42. Google Fonts API <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine|Inconsolata"/> <style> h1 { font-family: Tangerine, serif; font-size: 48px; text-shadow: 4px 4px 4px #aaa; } </style> </head> <body> <h1>Making the Web Beautiful!</h1> </body> </html> 38 @googledevlatam #devfest10Tuesday, November 2, 2010 38
  43. 43. Demo www.gobiernodechile.cl 39 @googledevlatam #devfest10Tuesday, November 2, 2010 39
  44. 44. HTML5Rocks.com 1.Step-by-Step Tutorials 2.Code Playground 3.Interactive Presentation 4.Studio / Gallery 40 @googledevlatam #devfest10Tuesday, November 2, 2010 40
  45. 45. Is HTML5 Ready? 41 @googledevlatam #devfest10Tuesday, November 2, 2010 41
  46. 46. Text caniuse.com 42 Google Developer Day 2010Tuesday, November 2, 2010 42
  47. 47. Modernizr Library • BAD: checking navigator.userAgent • Unreliable - users change this! • BETTER: Feature detection • Tests 20+ HTML5/CSS3 features: document.createElement(‘nav’) • Global Modernizr object with boolean property for each feature • Adds classes to the <html> element that explain precisely what features are (and are not) natively supported 43 @googledevlatam #devfest10Tuesday, November 2, 2010 43
  48. 48. Usage <div id="audio"> <audio> <source src="mySong.ogg" /> <source src="mySong.mp3" /> </audio> <button id="play">Play</button> <button id="pause">Pause</button> </div> /* In your CSS: */ .no-audio #audio { display: none; /* Dont show Audio options */ } .audio #audio button { /* Style the Play and Pause buttons nicely */ } // In your JavaScript: if (Modernizr.audio) { // Hook up functionality to Play and Pause buttons } 44 @googledevlatam #devfest10Tuesday, November 2, 2010 44
  49. 49. Google Chrome Frame 1.Add a single meta tag to your site • if !installed: direct users to download • else: your site ‘just works’ <meta http-equiv="X-UA-Compatible" content="chrome=1"> 2.Add a response header X-UA-Compatible: chrome=1 45 @googledevlatam #devfest10Tuesday, November 2, 2010 45
  50. 50. Thanks! • Tools • Google Fonts API: code.google.com/apis/webfonts/ • html5rocks.com • Compatibility: • Google Chrome Frame: http://code.google.com/chrome/chromeframe/ • caniuse.com • modernizr.com • File bugs against Chrome: crbug.com • Stay in Touch! • Twitter: @ChromiumDev • groups.google.com/a/chromium.org/group/chromium-html5/ 46 @googledevlatam #devfest10Tuesday, November 2, 2010 46
  51. 51. Questions? Stay up to date: @googledevbr 47 @googledevlatam #devfest10Tuesday, November 2, 2010 47
  52. 52. Tuesday, November 2, 2010 48

×