~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/atlibs

0
0
main
13 lines · 606 B Raw History
// 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));
		}
	};
}