SlideShare a Scribd company logo
1 of 49
Download to read offline
Practical HTML5:
Using It Today
Doris Chen Ph.D.
Developer Evangelist
Microsoft
doris.chen@microsoft.com
http://blogs.msdn.com/dorischen/
@doristchen
Who am I?
 Developer Evangelist at Microsoft based in Silicon
  Valley, CA
    Blog: http://blogs.msdn.com/b/dorischen/
    Twitter @doristchen
    Email: doris.chen@microsoft.com
 Has over 15 years of experience in the software industry
  focusing on web technologies
 Spoke and published widely at JavaOne, O'Reilly, Silicon
  Valley Code Camp, SD West, SD Forum and worldwide
  User Groups meetings
 Doris received her Ph.D. from the University of California
  at Los Angeles (UCLA)
Agenda
         Browser Fragmentation


         Feature Detection


         Polyfills and Shims


         Polyfills and Shims: Examples


         Summary and Resources



PAGE 3
Browser Fragmentation
Non-Modern Browsers
   Most non-modern browsers have trouble
      Non-modern Browsers (ref: caniuse.com)
         IE 6 - 8
         Firefox 3.6 and below
         Safari 4.0 and below
         Chrome 7
         Opera 10.x and below

   Even modern browsers have issues
   Varying levels of feature support across all major
    browsers
Browser Fragmentation
Fragmentation
 Varying Levels of Support
   Across browsers
   Across browser versions
   New versions released
    constantly
 Browser detection doesn’t
  work
   Fixes based on assumptions
   Full-time job tracking
    changes
Feature Detection
Feature Detection
 Based on what browsers support, not their versions
 Check for the feature you want to use
   Object, Method, Property, Behavior

 Detect for standards-based features
  first
     Browsers often support both standards and
      legacy
     Standards are your most stable ground to build
      upon
 Dynamically load custom code to mimic missing
  features
Why not Check for a
Browser?
 Bad
 // If not IE then use addEventListener…
 if (navigator.userAgent.indexOf("MSIE") == -1) {

     window.addEventListener( “load”, popMessage, false );

 } else if (window.attachEvent) {

     window.attachEvent( “onload”, popMessage);

 }
Why not Check for a
Browser?
Good
 if (window.addEventListener) {

      window.addEventListener( “load”, popMessage,
 false );

 } else if (window.attachEvent) {

     window.attachEvent( “onload”, popMessage);

 }
Demo
Feature Detection
What Happens When Feature Detection
Looks Like This…
Yuck! Even the monkey is freaked!
 function(){

        var
        sheet, bool,
        head = docHead || docElement,
        style = document.createElement("style"),
        impl = document.implementation || { hasFeature: function() { return false; } };

        style.type = 'text/css';
        head.insertBefore(style, head.firstChild);
        sheet = style.sheet || style.styleSheet;

        var supportAtRule = impl.hasFeature('CSS2', '') ?
             function(rule) {
                if (!(sheet && rule)) return false;
                var result = false;
                try {
                    sheet.insertRule(rule, 0);
                    result = (/src/i).test(sheet.cssRules[0].cssText);
                    sheet.deleteRule(sheet.cssRules.length - 1);
                } catch(e) { }
                return result;
             }:
             function(rule) {
                if (!(sheet && rule)) return false;
                sheet.cssText = rule;

                  return sheet.cssText.length !== 0 && (/src/i).test(sheet.cssText) &&
                   sheet.cssText
                       .replace(/r+|n+/g, '')
                       .indexOf(rule.split(' ')[0]) === 0;
             };

        bool = supportAtRule('@font-face { font-family: "font"; src: url(data:,); }');
        head.removeChild(style);
        return bool;
   };
Feature Detection
 Best option in my opinion for this…
 http://www.modernizr.com/
 Best feature detection Support
 Detects:
   All major HTML5 features
   All major CSS3 features
 Includes HTML5Shim for semantic tag support
 Widespread adoption
   Twitter, National Football League, Burger King,
    and many more…
 Constantly updated
 Shipping with ASP.NET MVC 3 Tools update
Get Custom Build
Test for @font-face
You can do this
           function(){

                  var
                  sheet, bool,
                  head = docHead || docElement,
                  style = document.createElement("style"),
                  impl = document.implementation || { hasFeature: function() { return false; } };

                  style.type = 'text/css';
                  head.insertBefore(style, head.firstChild);
                  sheet = style.sheet || style.styleSheet;

                  var supportAtRule = impl.hasFeature('CSS2', '') ?
                       function(rule) {
                          if (!(sheet && rule)) return false;
                          var result = false;
                          try {
                              sheet.insertRule(rule, 0);
                              result = (/src/i).test(sheet.cssRules[0].cssText);
                              sheet.deleteRule(sheet.cssRules.length - 1);
                          } catch(e) { }
                          return result;
                       }:
                       function(rule) {
                          if (!(sheet && rule)) return false;
                          sheet.cssText = rule;

                            return sheet.cssText.length !== 0 && (/src/i).test(sheet.cssText) &&
                             sheet.cssText
                                 .replace(/r+|n+/g, '')
                                 .indexOf(rule.split(' ')[0]) === 0;
                       };

                  bool = supportAtRule('@font-face { font-family: "font"; src: url(data:,); }');
                  head.removeChild(style);
                  return bool;
             };
Test for @font-face
Or ….




        if (Modernizr.fontface){
        …
        }
Demo
Polyfills and Shims
Polyfills & Shims

   What are they?
     Typically JavaScript, HTML & CSS code
   What do they do?
     Provides the technology that you, the developer,
      expect the browser to provide natively
     Provides support for missing features
   When do you use them?
     Use them to fallback gracefully or mimic
      functionality
What’s the Difference?

   Polyfill:
      Replicates the real, standard feature API
      You can develop for the future

   Shims
      Provides own API to a missing feature
      Doesn’t adhere to a specification but fills the
       gap
      Generally provides more features
Polyfills & Shims

   Big List of Polyfills: http://bit.ly/b5HV1x
      Some are good, some not so good
   Some frequently used Polyfills & Shims
      Polyfill:
          HTML5Shim - Semantic tag support
          Storage Polyfill - HTML5 localStorage
          H5F – Simulates new HTML5 form types
      Shims:
          Amplify Store – persistent client-side storage using
           localStorage, globalStorage, sessionStorage & userData
          easyXDM – Cross-domain messaging
Consider This
 You need to vet the code
   Does it work as expected?
   Cross-browser?
 You may need to support it in the future
   Developer abandons work
   Do you have the skills to maintain it?
 API Consistency
   Will you need to rewrite your code later?
Polyfills & Shims: Examples
  Semantic Tags
  Video Tags
  Media Queries
HTML5 Semantics
Semantic Document Structure
 HTML5 introduces a new semantic
  structure
     Replacing the use of DIV, SPAN
                                            HEADER
      and other elements with class and
      ID attributes
 New elements include header, nav,           NAV
  article, section, aside, and footer

                                          ARTICLE
                                                     ASIDE


                                            FOOTER
HTML5 Semantic Tags
Supported in Internet Explorer 9
<body>                                <mark>Doris dancing!</mark>
 <header>                             </section>
  <hgroup>                          </article>
   <h1>Doris Chen Dancing</h1>      ...
   <h2>Funky Town!</h2>             </section>
  </hgroup>
 </header>                           <aside>Aside items (i.e.
                                   links)</aside>
 <nav>
 <ul>Navigation links</ul>          <figure>
 </nav>                              <img src="..." />
                                     <figcaption>Doris
 <section>                         dancing</figcaption>
 <article>                          </figure>
  <header>
    <h1>Can you believe it?</h1>    <footer>Copyright © 2011</footer>
  </header>
  <section>                        </body>
HTML Tags
               <div id=”header”>

                 <div id=”nav”>




   <div id=”sidebar”>    <div id=”article”>




                <div id=”footer”>
New Semantic HTML Tags
                <header>

                 <nav>




                           <section>
      <aside>
                             <article>




                <footer>
Recognition & Styling
 Non-modern browsers don’t recognize the new
  tags
 Internal stylesheets not updated
 You can’t style elements not recognized
Demo
Semantic Tags
Polyfills & Shims: Examples
   Semantic Tags
   Video Tags
   Media Queries
HTML5 Video & Audio
 <audio     <video
 src=       src=       The url to the audio or video
            width=     The width of the video element
            height=    The height of the video element
            poster=    The url to the thumbnail of the video
 preload=   preload=   (none, metadata, auto) Start downloading
 autoplay   autoplay   Audio or video should play immediately
 loop       loop       Audio or video should return to start and play
 controls   controls   Will show controls (play, pause, scrub bar)
 >          >
 …          …
 </audio>   </video>
Compatibility Table
 HTML5 Audio




                                10.0.648.20
vCurrent    9     6     5.0.4                 11.01
                                     4


MP3 audio
            Yes   No    Yes        Yes        No (*)
support

WAV PCM
audio       No    Yes   Yes        Yes         Yes
support

AAC audio
            Yes   No    Yes        Yes        No (*)
format
Compatibility Table
HTML5 <video>




                                      10.0.648.20
vCurrent      9       6      5.0.4                  11.01
                                           4


VP8
(WebM)
                     Yes     No (*)      Yes         Yes
video
support
              Yes

H.264 video
                    No (*)    Yes       Yes (*)     No (*)
format
Elements With Fall Backs

          Browsers won’t render elements
          they don’t understand...

            For example:
                <video src=“video.mp4”>
                    What will it render?
                </video>


          But, they will render what’s
          between those elements


PAGE 37
HTML5 <video> : Degrading Gracefully
 Multiple video sources to support multiple browsers

   <video src="video.mp4" poster="movie.jpg"
       height="480" width="640"
       autoplay autobuffer controls loop>
    <source src="video.webm"
         type='video/webm; codecs="vp8, vorbis"' />
    <source src="video.mp4" />

   <!-- Flash/Silverlight video here -->
   <object type="application/x-silverlight-2" width="640" height="384">
          <param name="source" value="/resources/VideoPlayer10_01_18.xap"></param>
          <param name="initParams"
   value="m=http://mysite.com/video.mp4,autostart=true,autohide=true></param>
          <param name="background" value="#00FFFFFF"></param>
          <param name="x-allowscriptaccess" value="never"></param>
          <param name="allowScriptAccess" value="never" />
          <param name="wmode" value="opaque" />
        </object>

   </video>
Demo
Video, fall back
Polyfills & Shims: Examples
  Semantic Tags
  Video Tags
  Media Queries
Use Respond.js for Media Queries
  Respond.js
    Enable responsive web designs in browsers
    A fast polyfill for CSS3 Media Queries
       Lightweight: 3kb minified / 1kb gzipped
       for Internet Explorer 6-8 and more
    https://github.com/scottjehl/Respond
   <head>
      <meta charset="utf-8" />
      <link href="test.css" rel="stylesheet"/>
      <script src="../respond.min.js"></script>
   </head>
Demo
Use Respond for Media Queries
Realife: http://bostonglobe.com/
Yepnopejs
 Asynchronous conditional resource loader for JavaScript and CSS

 Integrated into Modernizr , only 1.6kb

 Load only the scripts that your users need

 Fully decouples preloading from execution
    full control of when your resource is executed
    change that order on the fly

 http://yepnopejs.com/
Yepnope Syntax

 yepnope([{
    test : /* boolean - Something truthy that you want to test */,
    yep : /* array (of strings) | string - The things to load if test is true */,
    nope : /* array (of strings) | string - The things to load if test is false */,
    both : /* array (of strings) | string - Load everytime */,
    load : /* array (of strings) | string - Load everytime */,
    callback : /* function ( testResult, key ) | object { key : fn } */,
    complete : /* function */
 }, ... ]);

PAGE 44
Yepnope and Modernizr
<script type="text/javascript"
src="yepnope.1.0.2-min.js"></script>
  <script type="text/javascript">
      yepnope({
          test : Modernizr.geolocation,
          yep : 'normal.js',
          nope : ['polyfill.js', 'wrapper.js']
      });
  </script>


PAGE 45
Demo
Yepnope, Modernizr
Take Away

   Avoid browser detection
      Browsers change
      Varying levels of feature support across all major browsers
   Use feature detection
      Check for the feature you want to use
      Detect for standards first
   Use Modernizr – http://modernizr.com
      Cleaner code & they’ve done the work for you
   Polyfills and Shims
      mimics a standard API to avoid a rewrite
Books
            Introducing HTML5
        (Bruce Lawson & Remy Sharp)


         HTML5 for Web Designers
               (Jeremy Keith)


          CSS3 for Web Designers
             (Dan Cederholm)
Practical HTML5: Using It Today

More Related Content

What's hot

Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQuery
Angel Ruiz
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
Div span__object_があればいい
Div  span__object_があればいいDiv  span__object_があればいい
Div span__object_があればいい
Shuhei Iitsuka
 

What's hot (20)

An in-depth look at jQuery UI
An in-depth look at jQuery UIAn in-depth look at jQuery UI
An in-depth look at jQuery UI
 
jQuery
jQueryjQuery
jQuery
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
前端概述
前端概述前端概述
前端概述
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 
Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5
 
Jquery ui
Jquery uiJquery ui
Jquery ui
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
Jquery-overview
Jquery-overviewJquery-overview
Jquery-overview
 
Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQuery
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Summit2014 topic 0066 - 10 enhancements that require 10 lines of code
Summit2014 topic 0066 - 10 enhancements that require 10 lines of codeSummit2014 topic 0066 - 10 enhancements that require 10 lines of code
Summit2014 topic 0066 - 10 enhancements that require 10 lines of code
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
jQuery Features to Avoid
jQuery Features to AvoidjQuery Features to Avoid
jQuery Features to Avoid
 
Jquery 5
Jquery 5Jquery 5
Jquery 5
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
Div span__object_があればいい
Div  span__object_があればいいDiv  span__object_があればいい
Div span__object_があればいい
 
Dr. Strangelove or: How I learned to stop worrying and love HTML, CSS and Jav...
Dr. Strangelove or: How I learned to stop worrying and love HTML, CSS and Jav...Dr. Strangelove or: How I learned to stop worrying and love HTML, CSS and Jav...
Dr. Strangelove or: How I learned to stop worrying and love HTML, CSS and Jav...
 

Viewers also liked

Viewers also liked (6)

A practical guide to building websites with HTML5 & CSS3
A practical guide to building websites with HTML5 & CSS3A practical guide to building websites with HTML5 & CSS3
A practical guide to building websites with HTML5 & CSS3
 
Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016
 
Angular mobile angular_u
Angular mobile angular_uAngular mobile angular_u
Angular mobile angular_u
 
Lastest Trends in Web Development
Lastest Trends in Web DevelopmentLastest Trends in Web Development
Lastest Trends in Web Development
 
Introduction to HTML5 and CSS3
Introduction to HTML5 and CSS3Introduction to HTML5 and CSS3
Introduction to HTML5 and CSS3
 
Presentation about html5 css3
Presentation about html5 css3Presentation about html5 css3
Presentation about html5 css3
 

Similar to Practical HTML5: Using It Today

6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides
MasterCode.vn
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
Alessandro Molina
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
Adam Lu
 
GDI Seattle Intermediate HTML and CSS Class 1
GDI Seattle Intermediate HTML and CSS Class 1GDI Seattle Intermediate HTML and CSS Class 1
GDI Seattle Intermediate HTML and CSS Class 1
Heather Rock
 
Rey Bango - HTML5: polyfills and shims
Rey Bango -  HTML5: polyfills and shimsRey Bango -  HTML5: polyfills and shims
Rey Bango - HTML5: polyfills and shims
StarTech Conference
 
C3 웹기술로만드는모바일앱
C3 웹기술로만드는모바일앱C3 웹기술로만드는모바일앱
C3 웹기술로만드는모바일앱
NAVER D2
 

Similar to Practical HTML5: Using It Today (20)

Styling components with JavaScript
Styling components with JavaScriptStyling components with JavaScript
Styling components with JavaScript
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
 
6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides
 
Web performance essentials - Goodies
Web performance essentials - GoodiesWeb performance essentials - Goodies
Web performance essentials - Goodies
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
 
Site optimization
Site optimizationSite optimization
Site optimization
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
GDI Seattle Intermediate HTML and CSS Class 1
GDI Seattle Intermediate HTML and CSS Class 1GDI Seattle Intermediate HTML and CSS Class 1
GDI Seattle Intermediate HTML and CSS Class 1
 
Rey Bango - HTML5: polyfills and shims
Rey Bango -  HTML5: polyfills and shimsRey Bango -  HTML5: polyfills and shims
Rey Bango - HTML5: polyfills and shims
 
Try AngularJS
Try AngularJSTry AngularJS
Try AngularJS
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
 
HTML & CSS 2017
HTML & CSS 2017HTML & CSS 2017
HTML & CSS 2017
 
What you need to know bout html5
What you need to know bout html5What you need to know bout html5
What you need to know bout html5
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
 
C3 웹기술로만드는모바일앱
C3 웹기술로만드는모바일앱C3 웹기술로만드는모바일앱
C3 웹기술로만드는모바일앱
 
Apex & jQuery Mobile
Apex & jQuery MobileApex & jQuery Mobile
Apex & jQuery Mobile
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
 

More from Doris Chen

Wins8 appfoforweb fluent
Wins8 appfoforweb fluentWins8 appfoforweb fluent
Wins8 appfoforweb fluent
Doris Chen
 
Dive Into HTML5
Dive Into HTML5Dive Into HTML5
Dive Into HTML5
Doris Chen
 

More from Doris Chen (20)

Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work Everywhere
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
 
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps FasterPractical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
 
What Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS AppsWhat Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS Apps
 
Windows 8 Opportunity
Windows 8 OpportunityWindows 8 Opportunity
Windows 8 Opportunity
 
Wins8 appfoforweb fluent
Wins8 appfoforweb fluentWins8 appfoforweb fluent
Wins8 appfoforweb fluent
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 Apps
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
 
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
 
Dive Into HTML5
Dive Into HTML5Dive Into HTML5
Dive Into HTML5
 
HTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and DesktopHTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and Desktop
 
Dive into HTML5: SVG and Canvas
Dive into HTML5: SVG and CanvasDive into HTML5: SVG and Canvas
Dive into HTML5: SVG and Canvas
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
Develop Netflix Movie Search App using jQuery, OData, JSONP and Netflix Techn...
Develop Netflix Movie Search App using jQuery, OData, JSONP and Netflix Techn...Develop Netflix Movie Search App using jQuery, OData, JSONP and Netflix Techn...
Develop Netflix Movie Search App using jQuery, OData, JSONP and Netflix Techn...
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Practical HTML5: Using It Today

  • 1. Practical HTML5: Using It Today Doris Chen Ph.D. Developer Evangelist Microsoft doris.chen@microsoft.com http://blogs.msdn.com/dorischen/ @doristchen
  • 2. Who am I?  Developer Evangelist at Microsoft based in Silicon Valley, CA  Blog: http://blogs.msdn.com/b/dorischen/  Twitter @doristchen  Email: doris.chen@microsoft.com  Has over 15 years of experience in the software industry focusing on web technologies  Spoke and published widely at JavaOne, O'Reilly, Silicon Valley Code Camp, SD West, SD Forum and worldwide User Groups meetings  Doris received her Ph.D. from the University of California at Los Angeles (UCLA)
  • 3. Agenda Browser Fragmentation Feature Detection Polyfills and Shims Polyfills and Shims: Examples Summary and Resources PAGE 3
  • 5. Non-Modern Browsers  Most non-modern browsers have trouble  Non-modern Browsers (ref: caniuse.com)  IE 6 - 8  Firefox 3.6 and below  Safari 4.0 and below  Chrome 7  Opera 10.x and below  Even modern browsers have issues  Varying levels of feature support across all major browsers
  • 7. Fragmentation  Varying Levels of Support  Across browsers  Across browser versions  New versions released constantly  Browser detection doesn’t work  Fixes based on assumptions  Full-time job tracking changes
  • 9. Feature Detection  Based on what browsers support, not their versions  Check for the feature you want to use  Object, Method, Property, Behavior  Detect for standards-based features first  Browsers often support both standards and legacy  Standards are your most stable ground to build upon  Dynamically load custom code to mimic missing features
  • 10. Why not Check for a Browser? Bad // If not IE then use addEventListener… if (navigator.userAgent.indexOf("MSIE") == -1) { window.addEventListener( “load”, popMessage, false ); } else if (window.attachEvent) { window.attachEvent( “onload”, popMessage); }
  • 11. Why not Check for a Browser? Good if (window.addEventListener) { window.addEventListener( “load”, popMessage, false ); } else if (window.attachEvent) { window.attachEvent( “onload”, popMessage); }
  • 13. What Happens When Feature Detection Looks Like This… Yuck! Even the monkey is freaked! function(){ var sheet, bool, head = docHead || docElement, style = document.createElement("style"), impl = document.implementation || { hasFeature: function() { return false; } }; style.type = 'text/css'; head.insertBefore(style, head.firstChild); sheet = style.sheet || style.styleSheet; var supportAtRule = impl.hasFeature('CSS2', '') ? function(rule) { if (!(sheet && rule)) return false; var result = false; try { sheet.insertRule(rule, 0); result = (/src/i).test(sheet.cssRules[0].cssText); sheet.deleteRule(sheet.cssRules.length - 1); } catch(e) { } return result; }: function(rule) { if (!(sheet && rule)) return false; sheet.cssText = rule; return sheet.cssText.length !== 0 && (/src/i).test(sheet.cssText) && sheet.cssText .replace(/r+|n+/g, '') .indexOf(rule.split(' ')[0]) === 0; }; bool = supportAtRule('@font-face { font-family: "font"; src: url(data:,); }'); head.removeChild(style); return bool; };
  • 14. Feature Detection  Best option in my opinion for this…  http://www.modernizr.com/
  • 15.  Best feature detection Support  Detects:  All major HTML5 features  All major CSS3 features  Includes HTML5Shim for semantic tag support  Widespread adoption  Twitter, National Football League, Burger King, and many more…  Constantly updated  Shipping with ASP.NET MVC 3 Tools update
  • 17. Test for @font-face You can do this function(){ var sheet, bool, head = docHead || docElement, style = document.createElement("style"), impl = document.implementation || { hasFeature: function() { return false; } }; style.type = 'text/css'; head.insertBefore(style, head.firstChild); sheet = style.sheet || style.styleSheet; var supportAtRule = impl.hasFeature('CSS2', '') ? function(rule) { if (!(sheet && rule)) return false; var result = false; try { sheet.insertRule(rule, 0); result = (/src/i).test(sheet.cssRules[0].cssText); sheet.deleteRule(sheet.cssRules.length - 1); } catch(e) { } return result; }: function(rule) { if (!(sheet && rule)) return false; sheet.cssText = rule; return sheet.cssText.length !== 0 && (/src/i).test(sheet.cssText) && sheet.cssText .replace(/r+|n+/g, '') .indexOf(rule.split(' ')[0]) === 0; }; bool = supportAtRule('@font-face { font-family: "font"; src: url(data:,); }'); head.removeChild(style); return bool; };
  • 18. Test for @font-face Or …. if (Modernizr.fontface){ … }
  • 19. Demo
  • 21. Polyfills & Shims  What are they?  Typically JavaScript, HTML & CSS code  What do they do?  Provides the technology that you, the developer, expect the browser to provide natively  Provides support for missing features  When do you use them?  Use them to fallback gracefully or mimic functionality
  • 22.
  • 23. What’s the Difference?  Polyfill:  Replicates the real, standard feature API  You can develop for the future  Shims  Provides own API to a missing feature  Doesn’t adhere to a specification but fills the gap  Generally provides more features
  • 24. Polyfills & Shims  Big List of Polyfills: http://bit.ly/b5HV1x  Some are good, some not so good  Some frequently used Polyfills & Shims  Polyfill:  HTML5Shim - Semantic tag support  Storage Polyfill - HTML5 localStorage  H5F – Simulates new HTML5 form types  Shims:  Amplify Store – persistent client-side storage using localStorage, globalStorage, sessionStorage & userData  easyXDM – Cross-domain messaging
  • 25. Consider This  You need to vet the code  Does it work as expected?  Cross-browser?  You may need to support it in the future  Developer abandons work  Do you have the skills to maintain it?  API Consistency  Will you need to rewrite your code later?
  • 26. Polyfills & Shims: Examples Semantic Tags Video Tags Media Queries
  • 27. HTML5 Semantics Semantic Document Structure  HTML5 introduces a new semantic structure  Replacing the use of DIV, SPAN HEADER and other elements with class and ID attributes  New elements include header, nav, NAV article, section, aside, and footer ARTICLE ASIDE FOOTER
  • 28. HTML5 Semantic Tags Supported in Internet Explorer 9 <body> <mark>Doris dancing!</mark> <header> </section> <hgroup> </article> <h1>Doris Chen Dancing</h1> ... <h2>Funky Town!</h2> </section> </hgroup> </header> <aside>Aside items (i.e. links)</aside> <nav> <ul>Navigation links</ul> <figure> </nav> <img src="..." /> <figcaption>Doris <section> dancing</figcaption> <article> </figure> <header> <h1>Can you believe it?</h1> <footer>Copyright © 2011</footer> </header> <section> </body>
  • 29. HTML Tags <div id=”header”> <div id=”nav”> <div id=”sidebar”> <div id=”article”> <div id=”footer”>
  • 30. New Semantic HTML Tags <header> <nav> <section> <aside> <article> <footer>
  • 31. Recognition & Styling  Non-modern browsers don’t recognize the new tags  Internal stylesheets not updated  You can’t style elements not recognized
  • 33. Polyfills & Shims: Examples Semantic Tags Video Tags Media Queries
  • 34. HTML5 Video & Audio <audio <video src= src= The url to the audio or video width= The width of the video element height= The height of the video element poster= The url to the thumbnail of the video preload= preload= (none, metadata, auto) Start downloading autoplay autoplay Audio or video should play immediately loop loop Audio or video should return to start and play controls controls Will show controls (play, pause, scrub bar) > > … … </audio> </video>
  • 35. Compatibility Table HTML5 Audio 10.0.648.20 vCurrent 9 6 5.0.4 11.01 4 MP3 audio Yes No Yes Yes No (*) support WAV PCM audio No Yes Yes Yes Yes support AAC audio Yes No Yes Yes No (*) format
  • 36. Compatibility Table HTML5 <video> 10.0.648.20 vCurrent 9 6 5.0.4 11.01 4 VP8 (WebM) Yes No (*) Yes Yes video support Yes H.264 video No (*) Yes Yes (*) No (*) format
  • 37. Elements With Fall Backs Browsers won’t render elements they don’t understand... For example: <video src=“video.mp4”> What will it render? </video> But, they will render what’s between those elements PAGE 37
  • 38. HTML5 <video> : Degrading Gracefully  Multiple video sources to support multiple browsers <video src="video.mp4" poster="movie.jpg" height="480" width="640" autoplay autobuffer controls loop> <source src="video.webm" type='video/webm; codecs="vp8, vorbis"' /> <source src="video.mp4" /> <!-- Flash/Silverlight video here --> <object type="application/x-silverlight-2" width="640" height="384"> <param name="source" value="/resources/VideoPlayer10_01_18.xap"></param> <param name="initParams" value="m=http://mysite.com/video.mp4,autostart=true,autohide=true></param> <param name="background" value="#00FFFFFF"></param> <param name="x-allowscriptaccess" value="never"></param> <param name="allowScriptAccess" value="never" /> <param name="wmode" value="opaque" /> </object> </video>
  • 40. Polyfills & Shims: Examples Semantic Tags Video Tags Media Queries
  • 41. Use Respond.js for Media Queries  Respond.js  Enable responsive web designs in browsers  A fast polyfill for CSS3 Media Queries  Lightweight: 3kb minified / 1kb gzipped  for Internet Explorer 6-8 and more  https://github.com/scottjehl/Respond <head> <meta charset="utf-8" /> <link href="test.css" rel="stylesheet"/> <script src="../respond.min.js"></script> </head>
  • 42. Demo Use Respond for Media Queries Realife: http://bostonglobe.com/
  • 43. Yepnopejs  Asynchronous conditional resource loader for JavaScript and CSS  Integrated into Modernizr , only 1.6kb  Load only the scripts that your users need  Fully decouples preloading from execution  full control of when your resource is executed  change that order on the fly  http://yepnopejs.com/
  • 44. Yepnope Syntax yepnope([{ test : /* boolean - Something truthy that you want to test */, yep : /* array (of strings) | string - The things to load if test is true */, nope : /* array (of strings) | string - The things to load if test is false */, both : /* array (of strings) | string - Load everytime */, load : /* array (of strings) | string - Load everytime */, callback : /* function ( testResult, key ) | object { key : fn } */, complete : /* function */ }, ... ]); PAGE 44
  • 45. Yepnope and Modernizr <script type="text/javascript" src="yepnope.1.0.2-min.js"></script> <script type="text/javascript"> yepnope({ test : Modernizr.geolocation, yep : 'normal.js', nope : ['polyfill.js', 'wrapper.js'] }); </script> PAGE 45
  • 47. Take Away  Avoid browser detection  Browsers change  Varying levels of feature support across all major browsers  Use feature detection  Check for the feature you want to use  Detect for standards first  Use Modernizr – http://modernizr.com  Cleaner code & they’ve done the work for you  Polyfills and Shims  mimics a standard API to avoid a rewrite
  • 48. Books Introducing HTML5 (Bruce Lawson & Remy Sharp) HTML5 for Web Designers (Jeremy Keith) CSS3 for Web Designers (Dan Cederholm)