Background – What is a Polyfill?
To polyfill the API, you simply just check if that API is available, and if not, load the polyfill that adds that API to your browser. That way, if your user is using the latest browser, you don’t punish them by downloading something they don’t need and hurting their performance.
How a Polyfill works
|window.Promise || document.write('<script src="https://email@example.com"></script>')|
|window.fetch || document.write('<script src="https://firstname.lastname@example.org"></script>')|
First, the code looks to see if the Promise API is available, because fetch relies on Promises in order to work. If the API is not available, it loads a script from a CDN that polyfills the Promise API. It does the same thing for the fetch API.
The built-in Script Tag Helper – CDN fallback
The fallback works for polyfills too!
The code above will generate nearly identical code to what’s in the first code sample. As mentioned above, fetch needs Promises to work, so I’m also polyfilling that conditionally as well. In the real world, I would likely bundle these two together (locally or using something like Polyfill.io) and make one network request, but using unpkg (an NPM CDN) was just for simplicity’s sake.
With the code above, I get the best of both worlds. My code using fetch runs on older browsers, but my users who use the latest browsers don’t take a network hit for something they don’t need. This same methodology will work for other ES2015 and above features and is nice for small apps that want to use some of the latest features and not have to deal with the build config of Babel or TypeScript transpiling down to ES5.
I’m not sure if this was an intended feature of the Script Tag Helper, but it’s a good use case for the fallback feature that I hadn’t seen anyone talk about, so I wanted to call attention to it.
And if you are lucky enough to only have to support Chrome at work. I assume this is you right now reading the hoops us plebes have to go through to get our code to run on all browsers: