RequireJS: Conditionally Load Polyfill Using Moder

2019-04-17 12:20发布

问题:

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