Skip to content

Instantly share code, notes, and snippets.

@wtfaremyinitials
Last active May 7, 2016 10:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtfaremyinitials/242d4bdbaf5cdc6dafe9 to your computer and use it in GitHub Desktop.
Save wtfaremyinitials/242d4bdbaf5cdc6dafe9 to your computer and use it in GitHub Desktop.
Feature detecting Promise polyfill
if(!window.Promise) {
var req = new XMLHttpRequest();
req.open('GET', 'https://cdn.polyfill.io/v2/polyfill.min.js?features=Promise', false);
req.send();
eval(req.responseText);
}

What's this?

A Promise polyfill that is only requested when the browser does not have support for Promises.

Note: You'll want to add this code to your application bundle rather than load it separately, otherwise you lose the main (efficiency) benefit of this polyfill.

Why add unnecessary complication?

The purpose of polyfill.io is that you can just include <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script> on your page and forget about feature dectection. What's the point in adding more complexity?

Adding that <script> tag means that every browser has to make another HTTP roundtrip before the application can run, even the ones that natively support Promises. Sure, the polyfill service will return an empty(ish) file, but making that request is still costly.

This way, only browsers that don't support Promises have to make the HTTP request.

Isn't synchronous XHR evil?

Yes, using XHR synchronously is generally bad for user experience. This is because synchronous XHR blocks all Javascript execution on the page. However, putting another <script> tag above your application blocks execution as well. This conditional synchronous XHR causes the page to only block on browsers that need it.

Isn't eval evil?

Only when the input code is untrusted. Putting untrusted code in a <script> tag is equally as bad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment