Practical HTML5: Using It Today

49
Doris Chen Ph.D. Developer Evangelist Microsoft [email protected] http://blogs.msdn.com/dorischen/ @doristchen Practical HTML5: Using It Today

description

Everyone wants to jump into HTML5 but how do you use the cool features of this new specification while ensuring older browsers render your web pages as expected? This is where Modernizr, polyfills and shims come in. In the session, you’ll learn the best practices and strategy to deal with new HTML5 and CSS3 features in old legacy browsers. You’ll learn step by step how to use specially crafted JavaScript and CSS code that emulate HTML5 features. With a couple of simple changes to your sites, you can take advantage of HTML5 today without breaking your sites in older browsers. Expect a lot of demos and code in the session.

Transcript of Practical HTML5: Using It Today

Page 1: Practical HTML5: Using It Today

Doris Chen Ph.D.

Developer Evangelist

Microsoft

[email protected]

http://blogs.msdn.com/dorischen/

@doristchen

Practical HTML5:

Using It Today

Page 2: Practical HTML5: Using It Today

Who am I?

Developer Evangelist at Microsoft based in Silicon Valley, CA

Blog: http://blogs.msdn.com/b/dorischen/

Twitter @doristchen

Email: [email protected]

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)

Page 3: Practical HTML5: Using It Today

Agenda

PAGE 3

Browser Fragmentation

Feature Detection

Polyfills and Shims: Examples

Summary and Resources

Polyfills and Shims

Page 4: Practical HTML5: Using It Today

Browser Fragmentation

Page 5: Practical HTML5: Using It Today

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

Page 6: Practical HTML5: Using It Today

Browser Fragmentation

Page 7: Practical HTML5: Using It Today

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

Page 8: Practical HTML5: Using It Today

Feature Detection

Page 9: Practical HTML5: Using It Today

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

Page 10: Practical HTML5: Using It Today

Why not Check for a Browser?

// 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);

}

Bad

Page 11: Practical HTML5: Using It Today

Why not Check for a Browser?

if (window.addEventListener) { window.addEventListener( “load”, popMessage, false ); } else if (window.attachEvent) { window.attachEvent( “onload”, popMessage); }

Good

Page 12: Practical HTML5: Using It Today

Feature Detection

Demo

Page 13: Practical HTML5: Using It Today

What Happens When Feature Detection Looks Like 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;

};

Yuck! Even the monkey is freaked!

Page 14: Practical HTML5: Using It Today

Feature Detection

Best option in my opinion for this…

http://www.modernizr.com/

Page 15: Practical HTML5: Using It Today

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

Page 16: Practical HTML5: Using It Today

Get Custom Build

Page 17: Practical HTML5: Using It Today

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 You can do this

Page 18: Practical HTML5: Using It Today

Test for @font-face Or ….

if (Modernizr.fontface){

}

Page 19: Practical HTML5: Using It Today

Demo

Page 20: Practical HTML5: Using It Today

Polyfills and Shims

Page 21: Practical HTML5: Using It Today

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

Page 22: Practical HTML5: Using It Today
Page 23: Practical HTML5: Using It Today

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

Page 24: Practical HTML5: Using It Today

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

Page 25: Practical HTML5: Using It Today

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?

Page 26: Practical HTML5: Using It Today

Polyfills & Shims: Examples

Semantic Tags

Video Tags

Media Queries

Page 27: Practical HTML5: Using It Today

HTML5 Semantics

HTML5 introduces a new semantic structure

Replacing the use of DIV, SPAN and other elements with class and ID attributes

New elements include header, nav, article, section, aside, and footer

Semantic Document Structure

HEADER

FOOTER

NAV

ARTICLE

ASIDE

Page 28: Practical HTML5: Using It Today

HTML5 Semantic Tags

<body> <header> <hgroup> <h1>Doris Chen Dancing</h1> <h2>Funky Town!</h2> </hgroup> </header> <nav> <ul>Navigation links</ul> </nav>

<section> <article> <header> <h1>Can you believe it?</h1> </header> <section>

<mark>Doris dancing!</mark>

</section> </article>

... </section> <aside>Aside items (i.e. links)</aside> <figure> <img src="..." /> <figcaption>Doris dancing</figcaption> </figure> <footer>Copyright © 2011</footer>

</body>

Supported in Internet Explorer 9

Page 29: Practical HTML5: Using It Today

<div id=”nav”>

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

<div id=”footer”>

<div id=”header”>

HTML Tags

Page 30: Practical HTML5: Using It Today

New Semantic HTML Tags

<nav>

<aside> <section>

<article>

<footer>

<header>

Page 31: Practical HTML5: Using It Today

Recognition & Styling Non-modern browsers don’t recognize the new

tags

Internal stylesheets not updated

You can’t style elements not recognized

Page 32: Practical HTML5: Using It Today

Semantic Tags

Demo

Page 33: Practical HTML5: Using It Today

Polyfills & Shims: Examples

Semantic Tags

Video Tags

Media Queries

Page 34: Practical HTML5: Using It Today

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>

Page 35: Practical HTML5: Using It Today

Compatibility Table HTML5 Audio

vCurrent 9 6 5.0.4 10.0.648.20

4 11.01

MP3 audio

support Yes No Yes Yes No (*)

WAV PCM

audio

support

No Yes Yes Yes Yes

AAC audio

format Yes No Yes Yes No (*)

Page 36: Practical HTML5: Using It Today

Compatibility Table HTML5 <video>

vCurrent 9 6 5.0.4 10.0.648.20

4 11.01

VP8

(WebM)

video

support

Yes

Yes No (*) Yes Yes

H.264 video

format No (*) Yes Yes (*) No (*)

Page 37: Practical HTML5: Using It Today

Elements With Fall Backs

PAGE 37

Browsers won’t render elements

they don’t understand...

But, they will render what’s

between those elements

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

Page 38: Practical HTML5: Using It Today

HTML5 <video> : Degrading Gracefully

<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>

Multiple video sources to support multiple browsers

Page 39: Practical HTML5: Using It Today

Video, fall back

Demo

Page 40: Practical HTML5: Using It Today

Polyfills & Shims: Examples

Semantic Tags

Video Tags

Media Queries

Page 41: Practical HTML5: Using It Today

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>

Page 42: Practical HTML5: Using It Today

Use Respond for Media Queries

Realife: http://bostonglobe.com/

Demo

Page 43: Practical HTML5: Using It Today

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/

Page 44: Practical HTML5: Using It Today

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

Page 45: Practical HTML5: Using It Today

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

Page 46: Practical HTML5: Using It Today

Yepnope, Modernizr

Demo

Page 47: Practical HTML5: Using It Today

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

Page 48: Practical HTML5: Using It Today

Introducing HTML5

(Bruce Lawson & Remy Sharp)

HTML5 for Web Designers

(Jeremy Keith)

CSS3 for Web Designers

(Dan Cederholm)

Books

Page 49: Practical HTML5: Using It Today