Controlling cache with javascript

Cache API

The awesome ServiceWorker API is meant to give developers a bit more control over what is and isn’t cached, and how. Sure we can play games with ETags and the like but doing it programmatically with JavaScript just feels better, more controllable. As with every API, however, adding stuff to cache isn’t just fun and games — you have to do the cleanup work yourself too, and by «cleanup work» I mean having to delete cache.

Let’s have a look at how you can get caches, add and delete requests from caches, and how you can then delete an entire cache!

Detecting the cache API

To detect if the browser supports the Cache API.

. check for the presence of the caches object within the window .

Creating a Cache

Creating a cache requires a caches.open call with a cache name:

caches.open('test-cache').then(function(cache) < // Cache is created and accessible >);

The caches.open call returns a Promise and the cache object that was either created or existed before the open call.

Читайте также:  Все морфы тигрового питона

Adding to Cache

You can think of a cache as an array of Request objects which act as keys to their responses which are stored by the browser. Simple addition to cache is happens via two main methods: add and addAll . You can provide these methods a string for the URL that should be fetched and cached or a Request object. You can learn more about Request objects by reading my fetch API post.

To batch add URLs to cache, you can use the addAll method:

caches.open('test-cache').then(function(cache) < cache.addAll(['/', '/images/logo.png']) .then(function() < // Cached! >); >);

The addAll method accepts an array of URLs whose URLs and responses should be cached. addAll returns a Promise. To add a single URL, use the add method:

caches.open('test-cache').then(function(cache) < cache.add('/page/1'); // "/page/1" URL will be fetched and cached! >);

add can also accept a custom Request :

caches.open('test-cache').then(function(cache) < cache.add(new Request('/page/1', < /* request options */ >)); >);

Similar to add is put whereby you can add a URL and its Response object:

fetch('/page/1').then(function(response) < return caches.open('test-cache').then(function(cache) < return cache.put('/page/1', response); >); >);

Exploring Cache

To view requests that have already been cached, you can use the individual cache’s keys method to retrieve an array of cached Request objects:

caches.open('test-cache').then(function(cache) < cache.keys().then(function(cachedRequests) < console.log(cachedRequests); // [Request, Request] >); >); /* Request < bodyUsed: false credentials: "omit" headers: Headers integrity: "" method: "GET" mode: "no-cors" redirect: "follow" referrer: "" url: "https://fullhost.tld/images/logo.png" >*/

If you’d like to view the response of a cached Request , you can do so by using cache.match or cache.matchAll :

caches.open('test-cache').then(function(cache) < cache.match('/page/1').then(function(matchedResponse) < console.log(matchedResponse); >); >); /* Response < body: (. ), bodyUsed: false, headers: Headers, ok: true, status: 200, statusText: "OK", type: "basic", url: "https://davidwalsh.name/page/1" >*/

You can learn more about Response objects by reading my fetch API post.

Removing a Cached Request

To remove a request from cache, use the cache’s delete method:

caches.open('test-cache').then(function(cache) < cache.delete('/page/1'); >);

The cache will no longer contain /page/1 !

Getting Existing Cache Names

To get the names of existing caches, use caches.keys :

caches.keys().then(function(cacheKeys) < console.log(cacheKeys); // ex: ["test-cache"] >);

window.caches.keys() again returns a promise.

Deleting A Cache

Deleting a cache is simple once you have cache key name:

caches.delete('test-cache').then(function() < console.log('Cache successfully deleted!'); >);

You’ll often delete a cache when you’re replacing with a new one (to trigger re-installation of a new service worker):

// Assuming `CACHE_NAME` is the newest name // Time to clean up the old! var CACHE_NAME = 'version-8'; // . caches.keys().then(function(cacheNames) < return Promise.all( cacheNames.map(function(cacheName) < if(cacheName != CACHE_NAME) < return caches.delete(cacheName); >>) ); >);

You’ll want to keep these snippets in your toolbox for when you look to become a service worker expert. Chrome and Firefox now have service worker support so you’ll be seeing many more sites/apps available (reliably) offline and loading at much faster rates. Enjoy!

Источник

The Cache API in JavaScript, and how to use it

The Cache API in JavaScript, and how to use it

Caching involves storing frequently accessed data in a fast-access storage medium, such as memory, so that subsequent requests for the same data can be served quickly without having to go through the full process of retrieving it from the source. This article explains JavaScript’s Cache API so you can enhance the performance of your websites.

Cache API is a browser API that provides developers with a way to store and retrieve data in a cache. It was first introduced in 2015 as part of the Service Worker API, which allows web developers to write scripts that run in the background of a web page and interact with the browser’s network requests. The Cache API allows developers to cache web resources, such as HTML pages, JavaScript files, images, and other assets so that they can be accessed quickly and efficiently. It is useful for progressive web applications (PWAs), which rely heavily on caching to deliver fast and responsive user experiences. In web development, performance is an important aspect of a positive user experience. One way to improve performance is by using the Cache API in JavaScript. This API allows developers to store web resources like images, fonts, and scripts in the user’s browser cache, reducing server requests and improving load times. It provides a simple interface for storing and retrieving network resources and the ability to manage and delete resources from the cache. In this article, you will learn how to use the Cache API to store and retrieve resources from the cache.

Checking for Cache API Support

The Cache API is supported in most modern browsers, including Chrome, Firefox, Safari, and Edge. Before using the Cache API, checking if the browser supports it is important. To check if the browser supports the Cache API, we can use the code below:

if ('caches' in window)  // Cache API is supported //You can add your code here > else  // Cache API is not supported >

In cases where the Cache API is not available, developers can use other caching mechanisms such as local storage, to store data on the client-side. They can also use server-side caching solutions, such as Redis, to store data on the server side. Another option is using a third-party library provides a similar caching mechanism that is compatible with a wide range of browsers. These libraries can help bridge the gap between different browsers and environments. It is always a good idea to provide fallback options for users who don’t have access to the Cache API or other caching mechanisms. This could involve using default values or retrieving data from the server if the cache is unavailable. Also, use proper error handling techniques, such as logging errors to the console.

Opening a Cache

We use the caches.open() method to open a cache. This method takes a string as a parameter, representing the name of the cache we want to open. If the cache does not exist, it will be created. Here’s an example:

caches.open('my-cache').then(function(cache)  // Cache opened successfully >).catch(function(error)  // Failed to open cache >);

Here, the code opens a cache named my-cache and returns a promise that resolves with the cache object if successful. If an error occurs, the promise is rejected with an error object.

Adding resources to the Cache

There are three (3) ways to add resources to the cache, they are:

Let’s go over each of these methods.

Cache.add()

In this method, Cache.add() takes a URL as an argument and adds the response from that URL to the cache. If the response is already in the cache, the method does nothing. For example:

caches.open("my-cache").then((cache) =>   cache  .add("/api/data")  .then(() => console.log("Data added to cache."))  .catch((error) => console.error("Error adding data to cache:", error)); >);

In the code above, you open a cache named my-cache and then add the response from the URL /api/data to the cache. If the operation is successful, you log a message to the console. If there’s an error, you log an error message instead.

Cache.addAll()

This method takes an array of URLs as an argument and adds the responses from those URLs to the cache. If any responses are already in the cache, the method skips them.

const urls = ["/api/data1", "/api/data2", "/api/data3"]; caches.open("my-cache").then((cache) =>   cache  .addAll(urls)  .then(() => console.log("Data added to cache."))  .catch((error) => console.error("Error adding data to cache:", error)); >);

In the example above, you define an array of URLs and then open a cache named my-cache . You can now use the Cache.addALL() method to add the responses from the URLs in the array to the cache. If the operation is successful, you log a message to the console. If there’s an error, you log an error message instead.

Cache.put()

The Cache.put() method works differently from the other methods; it takes a request object as an argument and adds the response from that request to the cache. If the response is already in the cache, the method overwrites it. Here’s an example:

const request = new Request("/api/data"); caches.open("my-cache").then((cache) =>  fetch(request)  .then((response) =>   cache  .put(request, response)  .then(() => console.log("Data added to cache."))  .catch((error) => console.error("Error adding data to cache:", error));  >)  .catch((error) => console.error("Error fetching data:", error)); >);

In the code above, you create a new request object for the URL /api/data and then open a cache named my-cache . You now fetch the request using the fetch() method and add the response to the cache using the Cache.put() method.

Session Replay for Developers

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.

Check our GitHub repo and join the thousands of developers in our community.

Retrieving resources from the Cache

The Cache API provides two primary methods for retrieving resources from the cache: match() and matchAll() . The match() method is used to retrieve a single resource from the cache, while the matchAll() method is used to retrieve all the resources that match a given request. Here is an example of how you can use the match() method to retrieve a single resource from the cache:

caches.open("my-cache").then(function (cache)   cache.match("/path/to/resource").then(function (response)  if (response)  // Resource found in cache  console.log(response);  > else  // Resource not found in cache  >  >);

Here, you first open the cache using the caches.open() method, which returns a promise that resolves to the cache object. You then use the match() method on the cache object to retrieve the resource at the specified path. If the resource is found in the cache, the match() method returns a response object that can be used to access the resource. If the resource is not found in the cache, the match() method returns null.

Below is an example of using the matchAll() method to retrieve all the resources that match a given request:

caches.open("my-cache").then(function (cache)   cache.matchAll("/path/to/*").then(function (responses)  if (responses.length > 0)  // Resources found in cache  console.log(responses);  > else  // No resources found in cache  >  >);

In this example, you use the matchAll() method to retrieve all the resources that match the pattern /path/to/* in the cache. The method returns an array of response objects that can be used to access the resources. If no resources are found in the cache, the matchAll() method returns an empty array.

Deleting resources from the Cache

When deleting resources from the cache, you use the cache.delete() method. This method takes a request object as a parameter, which represents the URL of the resource we want to delete. If the resource is found in the cache, it is deleted, and the method returns a promise that resolves to true . If the resource is not found in the cache, the method returns a promise that resolves to false . Here’s an example:

caches  .open("my-cache")  .then(function (cache)   cache.delete("/path/to/resource").then(function (isDeleted)  if (isDeleted)  // Resource deleted successfully  > else  // Resource not found in cache  >  .catch(function (error)  // Failed to delete resource from cache  >);

This code deletes the resource at the URL /path/to/resource from the my-cache cache. If the resource is found in the cache, it is deleted, and the isDeleted parameter is true .

Conclusion

By using the Cache API, you can reduce the time needed to fetch resources from the server and improve the overall user experience of your website. However, it’s important to note that caching should be used carefully and selectively to avoid caching resources that may change frequently. With proper use, the Cache API can help create fast and responsive websites.

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs and track user frustrations. Get complete visibility into your frontend with OpenReplay, the most advanced open-source session replay tool for developers.

A primer around WebRTC with everything you need to get started

Everything You Ever Wanted to Know About WebRTC

Learn what

Exciting New Features of Next JS v10

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs and track frustrations in your app. Get complete visibility into your frontend with OpenReplay, the most advanced open-source session replay tool for developers.

Источник

Оцените статью