Skip to content

Instantly share code, notes, and snippets.

@irealworlds
Created November 11, 2020 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irealworlds/b53b89be70b8af5768fd650efdcff7f4 to your computer and use it in GitHub Desktop.
Save irealworlds/b53b89be70b8af5768fd650efdcff7f4 to your computer and use it in GitHub Desktop.
Include files inside HTML, using a new custom tag, <include component="path">.
// Fix Array.from not being defined.
interface ArrayConstructor {
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
from<T>(arrayLike: ArrayLike<T>): Array<T>;
}
window.addEventListener("load", () => {
const needIncluding = Array.from(document.getElementsByTagName("include"));
for (const include of needIncluding) {
includeFile(include.getAttribute("component"), include);
}
});
const includeFile = async (fileName: string, target: Element) => {
const content = await getIncludeContent(fileName);
target.replaceWith(content);
return true;
}
const getIncludeContent = async (fileName: string) => {
const result = await (await fetch(fileName)).text();
const parser = new DOMParser();
return parser.parseFromString(result, "text/html").body;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment