UNPKG

2.14 kBMarkdownView Raw
1# @anansi/polyfill
2
3This 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
4feature detection and dynamic imports, allowing browsers that support the features to immediately progress.
5
6## Usage
7
8With React:
9
10```javascript
11import ReactDOM from 'react-dom';
12import loadPolyfills from '@anansi/polyfill';
13
14import MyApp from './App';
15
16async function init() {
17 await loadPolyfills();
18 ReactDOM.createRoot(document.body).render(<MyApp />);
19}
20init();
21```
22
23It's important to delay initilization of your app until these polyfills are loaded. This is provided
24by the promise returned by `loadPolyfills()`. Once that promise resolves all polyfills will be
25loaded into the `global` object.
26
27## Arguments
28
29### include: [`intl`, `ric`, `fetch`] | 'all' = 'all'
30
31By default all three polyfills are loaded, but if you don't use a feature (like `fetch`) you may
32want to avoid loading it. Do this by passing an array of features you want to include from
33[`intl`, `ric`, `fetch`].
34
35```javascript
36loadPolyfills(['intl', 'ric']); // fetch won't be loaded
37```
38
39## Supporting locales
40
41To support locales other than english, you'll need to import them as well. They weren't included
42to help with build times for sites that don't need it.
43
44### Support spanish and german:
45
46```javascript
47for (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
57import localeFinder from 'browser-locale';
58
59async 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```