Modernizr 与 Polyfill

之前提到,Modernizr 是 HTML5 和 CSS3 的特性检测工具,这里简单介绍一下它的用法。最简单的用法是在页面的 <head> 中添加 Modernizr 的 JavaScript 文件:

<!doctype html>
<html>
<head>
    <script src="modernizr-2.6.2.js"></script>
</head>
<body>
</body>
</html>

Modernizr 脚本执行后,你会发现页面类似下面的样子(以 IE9 为例):

<!doctype html>
<html class=" js no-flexbox no-flexboxlegacy canvas canvastext no-webgl no-touch geolocation postmessage no-websqldatabase no-indexeddb hashchange no-history draganddrop no-websockets rgba hsla multiplebgs backgroundsize no-borderimage borderradius boxshadow no-textshadow opacity no-cssanimations no-csscolumns no-cssgradients no-cssreflections csstransforms no-csstransforms3d no-csstransitions fontface generatedcontent video audio no-localstorage no-sessionstorage no-webworkers no-applicationcache svg inlinesvg no-smil svgclippaths">
<head>
    <script src="modernizr-2.6.2.js"></script>
</head>
<body>
</body>
</html>

可以看到,Modernizr 检测了数十个 HTML5 和 CSS3 特性之后,将结果记录在 html 标签的 class 属性中,其中带 no 前缀的表示浏览器不支持该特性,不带 no 前缀的表示浏览器支持该特性。这样,我们就可以根据 html 标签的这些 class 属性,在 CSS 文件中针对不同的特性应用不同的样式。例如 .no-touch #someid:hover #menu {display: block;}

Modernizr 脚本运行后也生成了一个 Modernizr 对象,以布尔值记录了上面所有这些特性。因此,我们就可以在 JavaScript 中简单地利用诸如 if (Modernizr.touch) {...} 这样的代码针对触屏设备作优化。 

但使用 CSS 的样式限制和 JavaScript 的条件判断,还是有个缺点:我们需要将各种可能性对应的代码都包含在 CSS 和 JavaScript 文件中,这样文件就变得很臃肿。针对这个问题,Modernizr 中包含了 YepNope.js 这个条件加载器,可以针对不同的特性加载不同的 CSS 和 JavaScript 文件。例如:

Modernizr.load({
  test: Modernizr.touch,
  yep : ['touch.css', 'touch.js'],
  nope: ['mouse.css', 'mouse.js'],
  complete: function() {
    doSomeThing();
  }
});

或者我们对缺乏某功能的浏览器加载 Polyfill(填充)库:

Modernizr.load({
  test: Modernizr.geolocation,
  yep : 'geo.js',
  nope: 'geo-polyfill.js'
});

参考资料:
[1] Modernizr: the feature detection library for HTML5/CSS3
[2] yepnope.js | A Conditional Loader For Your Polyfills!
[3] HTML5 Cross Browser Polyfills · Modernizr/Modernizr Wiki
[4] What is a Polyfill? - remy sharp’s b:log
[5] The Developer’s Guide To Writing Cross-Browser JavaScript Polyfills
[6] 图灵社区 : 阅读 : HTML5逸事:一袋“腻子粉”的故事

原文地址:https://www.cnblogs.com/zoho/p/3163154.html