This post is about clearing your local development cache with JavaScript without a server side language.
When we use a server side language to get our changes this is what happens:
1- the
Request is made by the browser to the server
2- the Response is sent from the server to
the browser
In this case, if any changes are made within the files, the server will
serve the browser with those changes.
But, what if you're not using a server side
language for your local development?!
If you're locally developing a website on the Classic Road (HTML + CSS + JS) without a
plugin in your IDE to synchronize your changes,
and have some generated cache, you'll have to refresh your page twice
and sometimes more to see the changes you've just made even if you're using a local
server as Laragon, WAMP, MAMP, XAMPP...
Did you ever asked yourself how much time
you're spending on refreshing twice?!
This is a time killer, it's very
annoying, and you're productivity will be affected!
The solution would be to clear the cache when we refresh the page, you would say "use Ctrl + F5!" and I would respond "go try it with your generated cache!".
To clear the cache when we hit the refresh button:
1- we'll have to access the
loading state
of the document without waiting for stylesheets,
images...
2- we'll have to open
the cache and access the particular
cache causing headaches
3- we'll have to delete
this particular cache!
if (document.readyState === "loading") {
// Loading hasn't finished yet
document.addEventListener("DOMContentLoaded", function () {
console.log("loading...")
caches.open("cacheNameCausingHeadaches").then(function (cache) {
cache.delete(document.URL).then(function () {
console.log("deleted")
})
})
})
}
Paste this code at the end of your scripts before the closing body tag and refresh your page twice for the last time!
To get the cacheNameCausingHeadeaches
:
caches.keys().then(function (keyList) {
console.log("keyList")
})
I'm here to share and learn 😊 so if you have a better way without an IDE plugin for a static site with some cache please let me know because I like to refresh and see the difference 😉
Hope this will be useful.