Skip to content

Instantly share code, notes, and snippets.

@vimtaai
Last active August 29, 2024 20:15
Show Gist options
  • Save vimtaai/b8aa63766b3a28e0093fb2d40c3c6177 to your computer and use it in GitHub Desktop.
Save vimtaai/b8aa63766b3a28e0093fb2d40c3c6177 to your computer and use it in GitHub Desktop.
Web components for inline importing HTML and SVG files
export class ImportBase extends HTMLElement {
static observedAttributes = ["src"];
async attributeChangedCallback(_1, _2, src) {
const response = await fetch(src);
if (response.ok) {
this.setHTMLUnsafe(await response.text());
this.onBeforeReplace();
this.replaceWith(...this.children);
}
}
onBeforeReplace() {}
}
import { ImportBase } from "./import-base.js";
class ImportHtml extends ImportBase {
onBeforeReplace() {
const scripts = this.querySelectorAll("script");
for (const script of scripts) {
const scriptClone = document.createElement("script");
for (const { name, value } of script.attributes) {
scriptClone.setAttribute(name, value);
}
scriptClone.textContent = script.textContent;
script.replaceWith(scriptClone);
}
}
}
customElements.define("import-html", ImportHtml);
import { ImportBase } from "./import-base.js";
class ImportSvg extends ImportBase {
onBeforeReplace() {
const svgElement = this.firstElementChild;
for (const { name, value } of this.attributes) {
svgElement.setAttribute(name, value);
}
svgElement.removeAttribute("src");
}
}
customElements.define("import-svg", ImportSvg);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment