RequireJS: Conditionally Load Polyfill Using Modernizr

久未见 提交于 2019-12-10 00:16:26

问题


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


回答1:


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.

First I wrapped it as an AMD module like this:

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

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();
    });
  }
});


来源:https://stackoverflow.com/questions/21190398/requirejs-conditionally-load-polyfill-using-modernizr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!