Arthur Guiot
Arthur Guiot

Reputation: 721

Browser cache is breaking my Client Side router

I'm developing a web app, and I use client-side routing (basically, we're loading the page using what's after the # in the URL).

But, I've noticed that sometimes when I go one page and I go on another one, the old one is loading instead of the new one. Let me explain when I click on the link to go wherever I want, the page I was on is loading.

I highly suspect that the browser cache is "overwriting" the new content.

And I still don't know why it only happens sometimes (especially when it's a new browser window).

Are there any solutions to force the browser to open the new page, like opening the page in another page, and closing the old tab?

EDIT

I'm currently using GitHub pages to host my project, so in your answer, make sure that everything is client side 😊.

Upvotes: 0

Views: 82

Answers (2)

Arthur Guiot
Arthur Guiot

Reputation: 721

I found a solution: open my link in a new tab, while closing the old one.

This can be done using the following code:

el.addEventListener("click", e => {
    e.preventDefault();
    window.open(el.href, "_blank")
    window.close()
})

Upvotes: 1

ayushgp
ayushgp

Reputation: 5101

You can set the following header from your server on all requests:

Cache-Control: no-cache 

This would disable caching for that file/response. If you're using a expressJS server, you can set it as:

function nocache(req, res, next) {
  res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
  res.header('Expires', '-1');
  res.header('Pragma', 'no-cache');
  next();
}

And use this function as a middleware for all the routes you want to disable caching for.

You can read more about cache headers on MDN Docs

Upvotes: 0

Related Questions