Created
December 7, 2022 13:25
-
-
Save malj/86902ffe5ce7c1d9ce06af4ee39220a1 to your computer and use it in GitHub Desktop.
<html-import src="path/to/file.html"></html-import>
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 default class HTMLImport extends HTMLElement { | |
#abortController = new AbortController() | |
async connectedCallback() { | |
let src = this.getAttribute("src") | |
if (src === null) { | |
console.warn("<html-import> element requires attribute \"src\"") | |
this.remove() | |
return | |
} | |
let url = new URL(src, location.origin) | |
if (url.href === location.href) { | |
console.warn("Circular HTML imports are not allowed") | |
this.remove() | |
return | |
} | |
try { | |
let res = await fetch(url, { signal: this.#abortController.signal }) | |
if (res.ok) { | |
let html = await res.text() | |
this.#abortController.signal.throwIfAborted() | |
this.outerHTML = html | |
} else { | |
throw res.headers.get("content-type") === "application/json" | |
? await res.json() | |
: new Error(await res.text()) | |
} | |
} catch (error) { | |
console.error(error) | |
this.remove() | |
} | |
} | |
disconnectedCallback() { | |
this.#abortController.abort() | |
} | |
} | |
customElements.define("html-import", HTMLImport) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment