Created
November 11, 2020 13:27
-
-
Save irealworlds/b53b89be70b8af5768fd650efdcff7f4 to your computer and use it in GitHub Desktop.
Include files inside HTML, using a new custom tag, <include component="path">.
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
// 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