Lazy Loading Polyfills
2 min readAs browsers ship new features, we gain better ways to manage our code. We hopefully don’t have to think about cross-browser concerns, and we can use the platform. However, if you’ve been in web development for any amount of time, you’ll soon realize that not all native elements provide the best experience. We use hacks, libraries, or full reimplementations. These aren’t ideal for maintainability and can increase the final output of our code that users have to download. If you haven’t used a polyfill before, they usually come in the form of a JavaScript library and add unsupported features in browsers before they are available.
In the last post, we looked at implementing a dialog component in React. Let’s look at how we can import the dialog polyfill lazily, so unsupported browsers still get the same experience, and we minimize the cost that supported browsers incur.
Today we are using the wonderful dialog-polyfill from the Chrome team. I put together a demo on Codesandbox if you would like to follow along.
If you use a bundler like Webpack or Parcel, you may have come across dynamic imports. These allow us to evaluate code lazily by invoking import as a function:
1import('dialog-polyfill')
When we invoke imports they return a promise when the file resolves. The resolved value will be the contents we fetched and allow us to interact with our code, in this case we will register the dialog polyfill with our dialog node:
1import('dialog-polyfill').then((polyfill) => {2 polyfill.registerDialog(document.querySelector('dialog'))3})
Finally, we add our feature detection to make sure this will only ever load on browsers that don’t support the dialog
element:
1if (window.HTMLDialogElement === undefined) {2 import('dialog-polyfill').then((polyfill) => {3 polyfill.registerDialog(document.querySelector('dialog'))4 })5}
That wasn’t too bad!
It won’t always be as easy to lazy-load features like this, but this simple pattern can be used to save users from having to download extra code that will never be executed. One last thing to note is you do not need a bundler depending on your browser support now that dynamic imports are a part of the spec.
- dialog
- polyfill
- tutorial