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?
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?
Share Improve this question asked Apr 22, 2015 at 17:24 Jamund FergusonJamund Ferguson 17k3 gold badges45 silver badges51 bronze badges2 Answers
Reset to default 15There 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
orrequire([])
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.
An simple (non-webpack) approach would be to do something like this in your HTML:
<script>
if (!window.Intl) { document.write('<script src="/js/Intl.min.js"><\/script>'); }
</script>
Though document.write
is not considered a best practice, this would provide a blocking approach to solving the problem, resulting in considerably less code in your the application. This solution does not use webpack, but may be a suitable solution for many people in this situation.