This article mainly introduces the behaviors object in the Polymer framework of JavaScript. Polymer is a Web UI related framework developed by Google. Friends in need can refer to it
Should localStorage be a household name? But there is much more to the local storage family than that. We talked about sessionStorage before, but now there is also a magical CacheStorage. It is used to store Response objects. In other words, it is used to cache HTTP responses. Although localStorage can also do it, it is probably more specialized.
The reference to CacheStorage on the browser is caches instead of cacheStorage in camel case, which is defined in the ServiceWorker specification. CacheStorage is a collection of multiple Cache, and each Cache can store multiple Response objects.
No more nonsense, here is the demo
<script> caches.delete('c1'); caches.delete('c2'); Promise.all([ caches.open('c1').then(function(cache) { return cache.put('/hehe', new Response('aaa', { status: 200 })); }), caches.open('c2').then(function(cache) { return cache.put('/hehe', new Response('bbb', { status: 200 })); }) ]).then(function() { return caches.match('/hehe'); }).then(function(response) { return response.text(); }).then(function(body) { console.log(body); }); </script>
First, call the open method on caches to get a reference to a Cache object asynchronously. On this object, we can put the Response object in (the parameters are a URL and a Response object) and use the match method to retrieve it (pass in a URL and retrieve the corresponding Response object).
The match method can be called not only on Cache but also on CacheStorage. For example, the above example opens two Cache and writes a URL called /hehe. After the write operation is completed, the match method is called on the external CacheStorage to match /hehe. The result is random (I can't find where this rule is defined).
Although the above example only puts one data to the Cache object, the Cache object itself can store more URL/Response pairs. And provides methods such as delete (user deletion) and keys (for traversal). However, Cache does not have a clear method like localStorage. If you must clear a Cache, you can directly delete the entire Cache on CacheStorage and reopen it.
This API is the same as ServiceWorker. It is usually used in ServiceWorker. The entire design style is also based on Promise like ServiceWorker.
The above is the entire content of this chapter. For more related tutorials, please visit JavaScript Video Tutorial!