Created
June 1, 2021 13:43
-
-
Save MohammadMD1383/83e322bfc0219ab5f75b5a45025eb39c to your computer and use it in GitHub Desktop.
includes the contents of a file to current position it is in a html document
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
class IncludeHtml extends HTMLElement { | |
static get observedAttributes(): Array<string> { | |
return ["url"]; | |
} | |
constructor() { | |
super(); | |
} | |
connectedCallback(): void { | |
const url: string = this.getAttribute("url"); | |
if (url) { | |
IncludeHtml.fetchHtml(url, (html: Node) => { | |
this.parentNode.insertBefore(html, this); | |
this.remove(); | |
}); | |
} else { | |
throw new Error("url not specified"); | |
} | |
} | |
private static fetchHtml(url: string, callback: Function): void { | |
const xhr = new XMLHttpRequest(); | |
xhr.onreadystatechange = () => { | |
if (xhr.readyState === 4 && xhr.status === 200) { | |
const template = document.createElement("template"); | |
template.innerHTML = xhr.responseText.trim(); | |
callback(template.content.firstChild); | |
} | |
}; | |
xhr.open("GET", url); | |
xhr.send(); | |
} | |
} | |
customElements.define("include-html", IncludeHtml); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment