Everyone wants to jump into HTML5 but how do you use the cool features of this new specification while ensuring existing and future browsers render your web pages as expected? This is where feature detection, Modernizr, polyfills and shims come in. In the session, you’ll learn the best practices and strategy to code with HTML5 and CSS3 features that won’t break for the existing and future browsers. You’ll learn step by step how to use specially crafted JavaScript and CSS code that emulate HTML5 features. Also, a real-life case study will be used to demonstrate step by step how to build Cross-Browser Plug-in-Free experiences. With a couple of simple changes to your sites, you can take advantage of HTML5 today without breaking your sites in the future. Expect a lot of demos and code in the session.
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
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
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 2 twitter @doristchen Blog http://blogs.msdn.com/dorischen
3. Agenda
Browser Fragmentation
Feature Detection
Polyfills and Shims
Polyfills and Shims: Examples
Summary and Resources
PAGE 3 twitter @doristchen Blog http://blogs.msdn.com/dorischen
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
PAGE 5 twitter @doristchen Blog http://blogs.msdn.com/dorischen
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
PAGE 7 twitter @doristchen Blog http://blogs.msdn.com/dorischen
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
PAGE 9 twitter @doristchen Blog http://blogs.msdn.com/dorischen
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);
}
PAGE 10 twitter @doristchen Blog http://blogs.msdn.com/dorischen
11. Why not Check for a
Browser?
Good
if (window.addEventListener) {
window.addEventListener( “load”, popMessage,
false );
} else if (window.attachEvent) {
window.attachEvent( “onload”, popMessage);
}
PAGE 11 twitter @doristchen Blog http://blogs.msdn.com/dorischen
12. 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;
};
PAGE 12 twitter @doristchen Blog http://blogs.msdn.com/dorischen
13. Feature Detection
Best option in my opinion for this…
http://www.modernizr.com/
PAGE 13 twitter @doristchen Blog http://blogs.msdn.com/dorischen
14. 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
PAGE 14
Shipping with ASP.NET MVC 3 Tools update
20. 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 20 twitter @doristchen Blog http://blogs.msdn.com/dorischen
22. 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 22 twitter @doristchen Blog http://blogs.msdn.com/dorischen
23. 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 23 twitter @doristchen Blog http://blogs.msdn.com/dorischen
24. 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 24 twitter @doristchen Blog http://blogs.msdn.com/dorischen
25. Polyfills & Shims: Examples
Semantic Tags
Video Tags
Media Queries
Conditional Resource Loader
26. 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
PAGE 26 twitter @doristchen Blog http://blogs.msdn.com/dorischen
29. New Semantic HTML Tags
<header>
<nav>
<section>
<aside>
<article>
<footer>
30. Recognition & Styling
Non-modern browsers don’t recognize the new
tags
Internal stylesheets not updated
You can’t style elements not recognized
PAGE 30 twitter @doristchen Blog http://blogs.msdn.com/dorischen
32. Polyfills & Shims: Examples
Semantic Tags
Video Tags
Media Queries
Conditional Resource Loader
33. 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>
34. 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
PAGE 34 twitter @doristchen Blog http://blogs.msdn.com/dorischen
35. 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 35 twitter @doristchen Blog http://blogs.msdn.com/dorischen
38. Polyfills & Shims: Examples
Semantic Tags
Video Tags
Media Queries
Conditional Resource Loader
39. 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 39 twitter @doristchen Blog http://blogs.msdn.com/dorischen
40. Use Respond for Media Queries
Realife: http://bostonglobe.com/
Demo
41. Polyfills & Shims: Examples
Semantic Tags
Video Tags
Media Queries
Conditional Resource Loader
42. 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 42 twitter @doristchen Blog http://blogs.msdn.com/dorischen
43. 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 43 twitter @doristchen Blog http://blogs.msdn.com/dorischen
44. 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 twitter @doristchen Blog http://blogs.msdn.com/dorischen
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 twitter @doristchen Blog http://blogs.msdn.com/dorischen
47. Building Cross Browser Plugin-free
Experiences
“Plug-in” refers broadly to browser extensions that run
native client code using low-level browser interfaces
Adobe Flash
ActiveX controls and Browser Helper Objects
Some of Webkit’s Approach
More browsers start to adopt plug-in-free approach
Lots of Web browsing simply don’t support plug-ins
IE 10 Metro
Browsers that do support plugins offer many ways to run
plugin free
YouTube http://www.youtube.com/html5
MSNBC plugin-free experience for rich media
Styles and Scripts
PAGE 47 twitter @doristchen Blog http://blogs.msdn.com/dorischen
49. Step 1: Declare Standards Mode and
Valid Markup for Modern Browsers
Ensure that you are operating in standards mode
Use valid markup
include the HTML5 doctype at the top of your document
<!DOCTYPE html>
PAGE 49 twitter @doristchen Blog http://blogs.msdn.com/dorischen
50. Step 2: Update CSS3 vendor prefixes
The CSS3 language is constantly in a state of change
New features suggested, updated, and standardized
For learning, browser vendors offer experimental
implementations via prefixed
Ensure that prefixes from each vendor are included in
your site
PAGE 50 twitter @doristchen Blog http://blogs.msdn.com/dorischen
52. Step 3: Get rid of browser Sniffing
methods
Methods to determine what the user’s browser and
device are capable of
if ( navigator.userAgent.indexOf("iPad") > -1 ) {
// Load HTML5 Experience
} else {
// Load Flash Experience
}
if ( tests.IE ) {
j = /msie.(d.d+)/i;
k = navigator.userAgent.match(j)[1];
}
The user agent string is not immutable
easily changed by plugins, or even the user.
Most modern browsers include the ability to easily change this value from
their development tools
PAGE 52 twitter @doristchen Blog http://blogs.msdn.com/dorischen
54. Feature Detection
Remove the browser sniffing code, and replace it with
feature detection code
if ( Modernizr.video ) {
// Load HTML5 Video
}
Or
if ( !!document.createElement(“video”).canPlayType ) {
// Load HTML5 Video
} else {
// Load Flash Video
}
PAGE 54 twitter @doristchen Blog http://blogs.msdn.com/dorischen
55. Use Fiddler (no direct access):
http://fiddler2.com
Modify remote files as though they were on
my local machine
A great way for testing changes without
the risk of breaking your live site
if (!(navigator.userAgent.toLowerCase().indexOf("ipad")>-1)){
// Flash Experience
}
Replace with:
if ( !document.createElement("video").canPlayType ) {
// Flash Experience
}
PAGE 55 twitter @doristchen Blog http://blogs.msdn.com/dorischen
58. 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
Use Yepnope
For conditional resource loader, work with Modernizr
PAGE 58 twitter @doristchen Blog http://blogs.msdn.com/dorischen
59. RESOURCES
• HTML5 Cheat Sheets
http://bit.ly/html5cheatsheets
• Free HTML5 Video Training
http://bit.ly/HTML5WebCampVideoTraining
• Feature-specific demos
• http://ie.microsoft.com/testdrive/
• Real-world demos
• http://www.beautyoftheweb.com/
PAGE 59 twitter @doristchen Blog http://blogs.msdn.com/dorischen