Last active
August 29, 2024 20:15
-
-
Save vimtaai/b8aa63766b3a28e0093fb2d40c3c6177 to your computer and use it in GitHub Desktop.
Web components for inline importing HTML and SVG files
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
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() {} | |
} |
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
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); |
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
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