Skip to content

Instantly share code, notes, and snippets.

@patrinhani-ciandt
Last active March 10, 2017 02:21
Show Gist options
  • Save patrinhani-ciandt/9117704165a69c7127b15651f5a147e4 to your computer and use it in GitHub Desktop.
Save patrinhani-ciandt/9117704165a69c7127b15651f5a147e4 to your computer and use it in GitHub Desktop.
Javascript Helper to turn easy to load a polyfill library just if necessary
/*
Usage Example:
window.PolyfillHelpers.loadPolyfillLib(
// Callback condition that says if the polyfill need to be loaded or not
function () { return ('Promise' in window); },
// Polyfill lib path
'/bower_components/es6-promise/es6-promise.auto.min.js', { async: false },
// Polyfill check/load completed
function(polyfillUsed) {
console.log('[PolyfillHelpers.loadPolyfillLib][Promise]->polyfillUsed: ', polyfillUsed);
}
);
*/
window.PolyfillHelpers = window.PolyfillHelpers || {};
;(function(PolyfillHelpers) {
PolyfillHelpers.loadPolyfillLib = function (checkCallback, polyfillPath, opt, onload) {
if (checkCallback) {
opt = opt || {};
opt.async = (opt.async === undefined) ? true : opt.async;
var cbResult = checkCallback();
if (!cbResult) {
var script = document.createElement('script');
script.async = opt.async;
script.src = polyfillPath;
script.onload = function () {
onload(true); /* param: polyfillUsed */
};
document.head.appendChild(script);
} else {
onload(false);
}
}
};
}(window.PolyfillHelpers));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment