The following example shows how to add a polyfill for addEventListener
.
- Determine if the feature needs to be polyfilled
You can use resources such as caniuse.com and developer.mozilla.org to check feature support.
In this example we’ve looked at caniuse addEventListener and seen that it’s not supported in IE8.
- Use polyfill.io service to generate the polyfill required
You can use the library to do this or use their CDN directly:
https://cdn.polyfill.io/v2/polyfill.js?features=Event&flags=always
Then save this in the same structure that is used in the main project (https://github.com/Financial-Times/polyfill-service/tree/master/packages/polyfill-library/polyfills)
- Use polyfill.io service to get detection script
We need to make sure we only run the polyfills if they’re needed.
We can take the associated detection code from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Event/detect.js
- Put everything together
(function(undefined) {
// Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Event/detect.js
var detect = (
// code goes here
)
if (detect) return
// Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Event&flags=always
// code goes here
}).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});