Skip to content

Instantly share code, notes, and snippets.

@ebidel
Last active November 11, 2017 00:13
Show Gist options
  • Save ebidel/219a208bdef6b3c5b814 to your computer and use it in GitHub Desktop.
Save ebidel/219a208bdef6b3c5b814 to your computer and use it in GitHub Desktop.
Helper method to imperatively load an (async) HTML import
/**
* Convenience for dynamically loading an HTML Import.
*
* This method creates a new `<link rel="import">` element with
* the provided URL and appends it to the document to start loading. By default,
* it loads async to not blocking rendering.
*
* @param {string} href The URL to load.
* @param {boolean} opt_async True if import should be async. Default: true.
* @return {Promise(HTMLLinkElement, Error)} A promise that resolves with the
* imported link element. Otherwise, an error.
*/
function importHref(href, async=true) {
return new Promise((resolve, reject) => {
var l = document.createElement('link');
l.rel = 'import';
l.href = href;
if (async) {
l.setAttribute('async', '');
}
l.onload = e => resolve(e.target);
l.onerror = reject;
document.head.appendChild(l);
});
}
// Usage
importHref('/elements/elements.html').then(link => {
console.log(link.import);
}, e => console.error(e));
// Load a bunch
Promise.all([
importHref('/elements.html'),
importHref('/elements2.html'),
importHref('/elements3.html')
]).then(values => {
values.forEach(val => console.log(val.import));
}, e => console.error(e));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment