Skip to content

Instantly share code, notes, and snippets.

@gdorsi
Last active May 12, 2018 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdorsi/d48cebcbba31406a58764f844bbe0e35 to your computer and use it in GitHub Desktop.
Save gdorsi/d48cebcbba31406a58764f844bbe0e35 to your computer and use it in GitHub Desktop.
A way to load custom elements polyfill dynamically
#!/usr/bin/env node
let [publicPath, outputPath] = process.argv.slice(2);
let path = require('path');
let { readFileSync, writeFileSync } = require('fs');
let { execSync } = require('child_process');
let shimPath = require.resolve(
'@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js'
);
let polyfillPath = require.resolve('@webcomponents/custom-elements');
let ceLoader = publicPath => `
(function() {
var newScript = document.createElement('script');
newScript.src = '${publicPath}' + (window.customElements ? 'ce-shim.js' : 'ce-polyfill.js');
newScript.onload = fire;
newScript.async = true;
document.head.appendChild(newScript);
function fire() {
var e;
if ('composed' in CustomEvent.prototype) {
e = new CustomEvent('CustomElementsPolyfillLoaded', {bubbles: true});
} else {
e = document.createEvent('CustomEvent');
e.initCustomEvent('CustomElementsPolyfillLoaded', true);
}
document.dispatchEvent(e);
window.CustomElementsReady = true;
}
})();
`;
execSync(`mkdir -p ${outputPath}`);
writeFileSync(path.join(outputPath, 'ce-shim.js'), readFileSync(shimPath));
writeFileSync(
path.join(outputPath, 'ce-polyfill.js'),
readFileSync(polyfillPath)
);
writeFileSync(
path.join(outputPath, 'ce-loader.js'),
ceLoader(publicPath),
'utf-8'
);
export let onCePolyfillLoad = fn => {
if (window.CustomElementsReady) return fn();
document.addEventListener('CustomElementsPolyfillLoaded', () => {
fn();
});
};
  • Generate the loader
node loader-generator.js my/js/base/urlpath my/js/loacal/path
  • Include it in yout HTML
  • Enjoy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment