Skip to content

Instantly share code, notes, and snippets.

@MohammadMD1383
Created June 1, 2021 13:43
Show Gist options
  • Save MohammadMD1383/83e322bfc0219ab5f75b5a45025eb39c to your computer and use it in GitHub Desktop.
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
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