1
2
3
4
5
6
7
8
9
10
11
12
13
// Base class for a custom element whose markup lives in an .html file of <template>s.
// Light DOM, so page CSS applies; use classes inside templates so a page can hold several.
export async function templated(url, id = "") {
const doc = new DOMParser().parseFromString(await (await fetch(url)).text(), "text/html");
const templates = Object.fromEntries([...doc.querySelectorAll("template")].map((t) => [t.id, t]));
return class extends HTMLElement {
static templates = templates;
connectedCallback() {
if (!this.childElementCount) this.append(templates[id].content.cloneNode(true));
}
};
}