Skip to content

Instantly share code, notes, and snippets.

@malj
Created December 7, 2022 13:25
Show Gist options
  • Save malj/86902ffe5ce7c1d9ce06af4ee39220a1 to your computer and use it in GitHub Desktop.
Save malj/86902ffe5ce7c1d9ce06af4ee39220a1 to your computer and use it in GitHub Desktop.
<html-import src="path/to/file.html"></html-import>
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