-
Notifications
You must be signed in to change notification settings - Fork 0
/
html-import-element.js
37 lines (29 loc) · 1.15 KB
/
html-import-element.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class HTMLImport extends HTMLElement {
async connectedCallback() {
// src should contain a relative link to the HTML file
const htmlSrc = this.getAttribute('src');
// fetch the content
const htmlResult = await fetch(htmlSrc);
if (!htmlResult.ok) {
// if we ran into an error, fail gracefully
return;
}
const htmlContent = await htmlResult.text();
// create an empty element to store new DOM
const empty = document.createElement('template');
empty.innerHTML = htmlContent;
// if any script tags are added, clone them
const scripts = empty.content.querySelectorAll('script');
scripts.forEach((script) => {
// Clone the script node
const clonedScript = document.createElement('script');
[...script.attributes].forEach((attr) => clonedScript.setAttribute(attr.name, attr.value));
clonedScript.textContent = script.textContent;
// replace the original script tag with this new one (which will cause it to trigger)
script.parentNode.replaceChild(clonedScript, script);
});
// replace this tag with the new content
this.replaceWith(...empty.content.childNodes)
}
}
customElements.define('html-import', HTMLImport)