Solution 1 :

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.

Problem :

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.

Comments

Comment posted by charlietfl

Use ajax to retrieve the html content

Comment posted by XMLHttpRequest()

Could you be more specific? I would thank you for it. I wanted to try something with the

Comment posted by charlietfl

Yes, or the more modern

Comment posted by example

Nice, the

Comment posted by Philippe Fanaro

Never mind, it is working. It’s just that Github Pages took a while to update its database, so it took a while for it to appear. Do you want to write an answer with something like what I wrote or do you prefer that I do it instead?

Comment posted by Philippe Fanaro

The real problem though is when you make a request to a page different than the main domain (

By