Use nomodule for polyfills

Avoid serving legacy JavaScript to modern browsers by adding the nomodule attribute to your polyfills.

A polyfill is a bit of code that adds functionality to a browser that you'd expect to be there, but may be missing.

It's often the case that your site may use a feature that exists in modern versions of Chrome, Firefox and Safari, but might not exist in Internet Explorer. Because you want to make sure your website still works for users on IE, you might include a polyfill to ensure that feature still works even for older, legacy browsers.

If you're using polyfills, you're likely hosting them as a separate JavaScript resource - either hosted on your site, or using a service like polyfill.io, in which case you'll see a <script> tag like this:

<script src="https://polyfill.io/v3/polyfill.js"></script>

While it's useful to give your visitors who are on a legacy browser your polyfill, the majority of your users will very likely be on a modern browser. Serving users with a modern browser a polyfill file would be unnecessary - and in the case of a third-party polyfill like polyfill.io, it will also cause a delay while a DNS/SSL connection is established to that new server, which can slow down your rendering and page load times.

But you can use the nomodule attribute here to ensure that legacy browsers download polyfill.js, but modern browsers don't.

<script nomodule src="https://polyfill.io/v3/polyfill.js"></script>

How does this work?

The nomodule attribute tells modern browsers (those that support module scripts) to ignore the <script> request. This means modern browsers won't attempt to fetch the polyfill.js file.

Older browsers, however, don't know what the nomodule attribute means so they'll ignore the attribute, and will download the script as normal.

As with all dev changes, we'd recommend testing this first on a staging server just to make sure that things don't accidentally break when it goes live. In particular, try using the site with an older browser when it's on staging just to be safe.

May 2021

Hello.

Thanks for reading. If you found this interesting, you might also like Blackbird - site speed monitoring for ecommerce. Try it for free today.