Last active
November 11, 2017 00:13
-
-
Save ebidel/219a208bdef6b3c5b814 to your computer and use it in GitHub Desktop.
Helper method to imperatively load an (async) HTML import
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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