Manually clearing the cache:
// Clear the entire cache
localStorage.clear();
sessionStorage.clear();<p></p>
Appending a cache-busting query parameter to the URL:
// Append a timestamp to the URL
window.location.href = <code>${window.location.origin}${window.location.pathname}?bust=${Date.now()}</code>;<p></p>
This technique forces the browser to fetch a new version of the resource by including a unique query parameter in the URL, which the browser will not cache.
Using the
Cache-Control
HTTP header:
// Set the Cache-Control header to prevent caching
fetch('/my-resource', {
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate'
}
});
The Cache-Control header can be used to control how the browser caches the response. Setting it to no-cache, no-store , and must-revalidate will prevent the browser from caching the response.
Invalidating the cache using the unload event:
window.addEventListener('unload', () => {
// Invalidate the cache here
localStorage.clear();
sessionStorage.clear();
});
The unload event is fired when the user navigates away from the page, and can be used to invalidate the cache before the page is unloaded.
Using a service worker to control caching:
// In your service worker script
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.open('my-cache').then((cache) => {
return cache.match(event.request).then((response) => {
if (response) {
return response;
}
return fetch(event.request.clone()).then((response) => {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
Service workers allow you to have more fine-grained control over caching, including the ability to invalidate the cache programmatically.
The choice of technique will depend on your specific use case and the requirements of your application. For example, if you need to invalidate the cache for a specific resource, using a cache-busting query parameter or the Cache-Control header might be the most appropriate approach. If you need to invalidate the cache for the entire application, using
localStorage.clear() or the unload event might be more suitable.