What is the Javascript Cache class for?

Asked

Viewed 215 times

13

I saw that Javascript has a class called Cache. From what little I could understand, it seems to have something to do with requisitions.

I wanted to know a little more about this class:

  • Does it serve exclusively for requests made with Request? Or could it be used with the standard Javascript Xtmlhttprequest?

  • This class can be used to cache something other than the one mentioned in the first question?

  • Where this cache is stored?

  • What is the support for this feature? If there is a lack of support, it is possible to do Polyfill?

  • 3

    Who gave the negative can explain what can be improved?

  • Since you posted on Stackoverflow in Portuguese, I think reading the documentation in Portuguese might help you, have you looked at it? https://developer.mozilla.org/en-US/docs/Web/API/Cache

  • @Fellipesanches I believe the question is about technical specifications regarding the implementation of the class Cache. So much so that the link you passed is included in the question.

2 answers

7

The Cache API obviously serves to manipulate the application cache, usually implemented with service worker to intercept requests made by the application

//Sempre que ocorrer uma requisição
self.addEventListener('fetch', function(event) {
    //Se a origem da requisição for um xhr, fetch ou semelhante
    //o valor da propriedade destination será uma string vazia ('')
    console.log(event.request.destination || 'fetch');
    event.respondWith(
        caches.open('MyCacheName').then(function(cache) {
            return cache.match(event.request, {
                ignoreSearch: true
            });
        }).then(function(response) {
            console.log(response ? 'from cahche' : 'from fetch')
            return response || fetch(event.request);
        })
    );
});

In the Fecthevent there is the property request of the kind Request which in turn has the atrium destination of the kind Requestdestination, it is a string that contains the destination of the answer, that is, where the request was made, the possible values are:

  • "" The Empty string is the default value of Destination. What does it Mean?

  • "audio" The target is audio data.

  • "audioworklet" The target is data being fetched for use by an audio worklet.

  • "Document" The target is a Document (HTML or XML).

  • "embed" The target is Embedded content.

  • "font" The target is a font.

  • "image" The target is an image.

  • "manifest" The target is a manifest.

  • "Object" The target is an Object.

  • "paintworklet" The target is a Paint worklet.

  • "report" The target is a report.

  • "script" The target is a script.

  • "serviceworker" The target is a service worker.

  • "sharedworker" The target is a Shared worker.

  • "style" The target is a style

  • "track" The target is an HTML .

  • "video" The target is video data.

  • "worker" The target is a worker.

  • "xslt" The target is an XLST Transform.

For requests made from the API fetch or XMLHttpRequest the value of destination is an empty string (""), but there are many other uses, and in fact this has no direct link to the Cache API, it can be used in this event, just as you can implement it outside the service worker

All caches made are stored in the global variable caches, it is a list of "cache groups", for example, I can organize my api caches according to the version (my-api-v1, my-api-v1.1, my-api-v2, etc). When "opening" a groups despair with cache.open you are returned a Promisse with an instance of Cache which can be used to store response requests

Despite being an experimental API, its compatibility is good, and is available in most browsers, you can see the complete and updated list on table of the MDN

There is Polyfill, I recently implemented the Cache API in a PWA using that, you can import into a service worker using the function importScripts

6


According to the specification:

The Object Cache represents a request Response list. Multiple Separate Objects implementing the Cache interface Across Documents and Workers can all be Associated with the same request Response list simultaneously.

In English free:

A Cache object represents a response list to the request. Multiple separate objects implementing the Cache interface across multiple documents and Workers can be associated with the same request response list simultaneously.

Answering your questions:

Does it serve exclusively for requests made with Request? Or could it be used with the standard Javascript Xtmlhttprequest?

No, only with Request. The cache is designed to be used in principle with Service Workers, and is part of its specification. The cache API only stores pairs of Request/Response objects, which respectively represent the HTTP request/Sponse protocol. The XMLHTTPRequest is very primitive and in general I wouldn’t recommend using it for anything. The fetch has plenty of support nowadays, plus a good polyfill.

In a way, the cache can be seen as a array of Request objects, functioning as answer keys, which the browser then stores.

This class can be used to cache something other than the one mentioned in the first question?

Through the request cache you can store almost all static content of an application. The cache is virtually all the content of a basic Serviceworker, and with it you can store fonts, pages (see explanation below), images, Javascript files, CSS, etc. Example:

Note that you don’t necessarily need Service Worker to use the API, for example to store static resources, you don’t need to:

// Verifica que o navegador tem suporte para a API
if('caches' in window) {
  // Faz o cache de `assets` como fonte e imagem
  caches.open('meuCacheAqui').then(objetoDoCache => {
    objetoDoCache.addAll([
      '/assets/fonts/suaFonte.woff',
      '/assets/img/imagemBemBonita.jpg'
    ])
    .then(_ => console.log('Cache Realizado!'))
  })
}

But if you want to store a page, then you would need a Service Worker to handle the browser request for offline resources. Couldn’t do it with the API Cache alone.

The reason you need a Serviceworker is that while a page can be read and written via a cache window.caches, you would need a Serviceworker to intercept the page’s initial request so you can reply with a cache.

Where this cache is stored?

In the browser itself, within the profile of the user who accessed the cache, within the storage of the Service Worker. In Chromium-based browsers, it stays inside the folder Service Worker. I can’t tell the others.

What is the support for this feature? If there is a lack of support, it is possible to do Polyfill?

For support, see the MDN. A very stable Polyfill can be found here.

Useful Links (English):

Browser other questions tagged

You are not signed in. Login or sign up in order to post.