I'm trying to create a simple blog where at least the <nav>
bar won't change, and so I would like to not have to load it on every single click.
To achieve this, I'm thinking about creating my posts in HTML files without the <head>
, the <body>
, etc., only, say, the <article>
tag and all the content inside it. Then, when the user clicks on a link, that content gets loaded onto the current page without the browser having to load a whole new page. But how exactly do I do this? How do I load/parse HTML from another file? — I'm new to creating single-page apps from scratch...
I know the DOMParser
can parse strings into HTML, but first I would have to open the file itself and read it as a string. Is this the way to do it? — I don't want to have to copy-paste my articles as template literals onto the code itself, that makes writing the HTML content quite annoying and unmanageable.
This is the current Github Pages website if you want to take a look at it.
You can use XMLHttpRequest()
, but, as @charlietfl points out, the fetch
API is much more natural.
function appendArticle(): void {
fetch("/articles/test.html")
.then((response: Response) => response.text())
.then((htmlAsString: string) => {
const parser: DOMParser = new DOMParser();
const articleDocument: Document = parser.parseFromString(htmlAsString, "text/html");
const article: HTMLElement = articleDocument.querySelector("article")!;
document.body.append(article);
});
}
// You don't need to use `document.onclick`, this is just an example...
document.onclick = (_: MouseEvent) => appendArticle();
That does work even in the Github Pages context. The only issue you might encounter is delay: while Github isn't able to update its servers' databases the fetch
operation will return null
and you willl at most see null
on the HTML screen.