RequireJS:使用Modernizr有条件地加载Polyfill [英] RequireJS: Conditionally Load Polyfill Using Modernizr

查看:156
本文介绍了RequireJS:使用Modernizr有条件地加载Polyfill的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将polyfill脚本包装为AMD模块并使用Modernizr和RequireJS有条件地加载它?

How do you wrap a polyfill script as an AMD module and conditionally load it using Modernizr and RequireJS?

(在我起草问题时想出了答案-向其他尝试做同样事情的人发布答案.)

(Figured it out while I was drafting my question - posting answer for anyone else trying to do the same thing.)

推荐答案

我需要加载的polyfill是 jquery -placeholder (不支持输入占位符的浏览器).它不提供现成的AMD支持.

The polyfill I needed to load was jquery-placeholder for browsers that don't support input placeholders. It does not provide AMD support out of the box.

首先,我将其包装为AMD模块,如下所示:

First I wrapped it as an AMD module like this:

define(['jquery'], function ($) {
  (function(window, document, $) {
    ... polyfill ...
  }(this, document, jQuery));
});

然后在main.js中,我使用Modernizr有条件地require() polyfill脚本:

Then in main.js I used Modernizr to conditionally require() the polyfill script:

require(['jquery', 'modernizr'], function ($, Modernizr) {
  if (!Modernizr.input.placeholder) {
    require(['jquery', 'placeholder'], function ($) {
      $('#input').placeholder();
    });
  }
});

这篇关于RequireJS:使用Modernizr有条件地加载Polyfill的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆