I'm using React-Intl with webpack and I need the Intl shim to support Safari and IE, but I don't want to load it for browsers that already support the Intl spec.
The polyfill is pretty huge (900kb), how can I ensure it only gets loaded in browsers that don't support it already?
There are a few things that you need to do.
Make sure to require intl/Intl
which loads the core library and not all of the associated countries. This will reduce the size of the library from from around 900kb to around 150kb.
Use webpack's require.ensure
or require([])
functions to dynamically require Intl.js only when needed. This will create a separate bundle for just the Intl.js file, which will be loaded on an as-needed basis.
lib/shim.js
// shim for Intl needs to be loaded dynamically
// so we callback when we're done to represent
// some kind of "shimReady" event
module.exports = function(callback) {
if (!window.Intl) {
require(['intl/Intl'], function(Intl) {
window.Intl = Intl;
callback();
});
} else {
setTimeout(callback, 0); // force async
}
};
app.js
var shimReady = require('lib/shim');
shimReady(startApp);
Note: You may also need access to country-specific information and properties. For my basic needs I didn't actually require this data, but if you do be sure to read the section on Intl.js website loading locale data.