1 | # @anansi/polyfill
|
2 |
|
3 | This ensures support for [Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) localization object, [requestIdleCallback](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) and [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). It does so using
|
4 | feature detection and dynamic imports, allowing browsers that support the features to immediately progress.
|
5 |
|
6 | ## Usage
|
7 |
|
8 | With React:
|
9 |
|
10 | ```javascript
|
11 | import ReactDOM from 'react-dom';
|
12 | import loadPolyfills from '@anansi/polyfill';
|
13 |
|
14 | import MyApp from './App';
|
15 |
|
16 | async function init() {
|
17 | await loadPolyfills();
|
18 | ReactDOM.createRoot(document.body).render(<MyApp />);
|
19 | }
|
20 | init();
|
21 | ```
|
22 |
|
23 | It's important to delay initilization of your app until these polyfills are loaded. This is provided
|
24 | by the promise returned by `loadPolyfills()`. Once that promise resolves all polyfills will be
|
25 | loaded into the `global` object.
|
26 |
|
27 | ## Arguments
|
28 |
|
29 | ### include: [`intl`, `ric`, `fetch`] | 'all' = 'all'
|
30 |
|
31 | By default all three polyfills are loaded, but if you don't use a feature (like `fetch`) you may
|
32 | want to avoid loading it. Do this by passing an array of features you want to include from
|
33 | [`intl`, `ric`, `fetch`].
|
34 |
|
35 | ```javascript
|
36 | loadPolyfills(['intl', 'ric']); // fetch won't be loaded
|
37 | ```
|
38 |
|
39 | ## Supporting locales
|
40 |
|
41 | To support locales other than english, you'll need to import them as well. They weren't included
|
42 | to help with build times for sites that don't need it.
|
43 |
|
44 | ### Support spanish and german:
|
45 |
|
46 | ```javascript
|
47 | for (const locale of ['es', 'de']) {
|
48 | import(
|
49 | /* webpackChunkName: "locale-request" */ `intl/locale-data/jsonp/${locale}.js`
|
50 | );
|
51 | }
|
52 | ```
|
53 |
|
54 | ### Detect locale of browser:
|
55 |
|
56 | ```javascript
|
57 | import localeFinder from 'browser-locale';
|
58 |
|
59 | async function init() {
|
60 | await loadPolyfills();
|
61 | if (
|
62 | !global.Intl ||
|
63 | typeof global.Intl.DateTimeFormat.prototype.formatToParts !== 'function'
|
64 | ) {
|
65 | const locale = localeFinder();
|
66 | await import(
|
67 | /* webpackChunkName: "locale-request" */ `intl/locale-data/jsonp/${locale}.js`
|
68 | );
|
69 | }
|
70 | ReactDOM.createRoot(document.body).render(<MyApp />);
|
71 | }
|
72 | ```
|