[PWA] 7. First Cache when installed

If you want your application works offline or lie-wifi. You need to use cache.

API:

Create Caches:

caches.open(‘cache_name‘).then( (cache) => {
    // create name if not exists yet, return cache if there is a one
})

Create single cache:

cache.put(request, response);

cache.addAll([
  ‘/foo‘,
  ‘/bar‘
])

Get the cache:

cache.match(request)

caches.match(request)

When to start cache:

We can do cache in ‘installing‘ service worker, what it will do is fetch everything we need from network and create cache for each of them.

self.addEventListener(‘install‘, function(event) {
  var urlsToCache = [
    ‘/‘,
    ‘js/main.js‘,
    ‘css/main.css‘,
    ‘imgs/icon.png‘,
    ‘https://fonts.gstatic.com/s/roboto/v15/2UX7WLTfW3W8TclTUvlFyQ.woff‘,
    ‘https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOD8E0i7KZn-EPnyo3HZu7kw.woff‘
  ];

  event.waitUntil(
    // TODO: open a cache named ‘wittr-static-v1‘
    // Add cache the urls from urlsToCache
      caches.open(‘wittr-static-v1‘)
          .then( (cache) => {
              cache.addAll(urlsToCache)
          })
          .catch( () => {
              console.error("Cannot cache anything");
          })
  );
});

Now we have create the cache, but it is not useful until we use the cache.

To use cache, we can do:

self.addEventListener(‘install‘, function(event) {
  var urlsToCache = [
    ‘/‘,
    ‘js/main.js‘,
    ‘css/main.css‘,
    ‘imgs/icon.png‘,
    ‘https://fonts.gstatic.com/s/roboto/v15/2UX7WLTfW3W8TclTUvlFyQ.woff‘,
    ‘https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOD8E0i7KZn-EPnyo3HZu7kw.woff‘
  ];

  event.waitUntil(
    // TODO: open a cache named ‘wittr-static-v1‘
    // Add cache the urls from urlsToCache
      caches.open(‘wittr-static-v4‘)
          .then( (cache) => {
              cache.addAll(urlsToCache)
          })
          .catch( () => {
              console.error("Cannot cache anything");
          })
  );
});

self.addEventListener(‘fetch‘, function(event) {
    event.respondWith(
        caches.match(event.request).then((response)=>{
            if(response){
                return response;
            }else{
                return fetch(event.request);
            }
        })
    )
});

So we use ‘caches.match‘ to get all the caches for request.

In the then block, cache is successfully fetched, we check whether there is cache data, if it is, then return the response;

If there is no cache data, then we fetch the data from real-server.

But this approach has some problem:

After we go offline mode, the pictures are not showing, this is because we only cache when the servcie worker is installed.

So here is some problem we need to solve:

时间: 2024-08-10 03:53:37

[PWA] 7. First Cache when installed的相关文章

Distributed Cache Coherence at Scalable Requestor Filter Pipes that Accumulate Invalidation Acknowledgements from other Requestor Filter Pipes Using Ordering Messages from Central Snoop Tag

A multi-processor, multi-cache system has filter pipes that store entries for request messages sent to a central coherency controller. The central coherency controller orders requests from filter pipes using coherency rules but does not track complet

WordPress缓存插件WP-Super-Cache安装使用

WP-Super-Cache插件使用:(wp-postviews插件会无法统计) ①前提是固定链接不可用默认的,上传WP-Super-Cache插件,不要急着启用. ②赋予以下权限:给wp-super-cache文件夹添加写权限.给wp-content文件夹添加写权限.在wp-content文件夹下新建cache文件夹并添加写权限. ③在网站根目录wp-config.php文件中define('DB_NAME'的上一行添加如下代码(也就是添加在wp-config.php文件中语句的最前面)def

[PWA] 8. Delete old cache and only keep one

So once you modify the code, service worker will auto create a new one and it won't take control over until the previous service work total die(close the tab or nav to a new url). The new service work is in the waiting list. Now what we want to do is

[PWA] Cache JSON Data in a React PWA with Workbox, and Display it while Offline

We can view the PWA offline because we are caching the static and CDN assets for the app - but the list of todo items won't display, because those API calls are not being cached. We'll add another route to the service worker, to store the result of a

[PWA] 15. Using The IDB Cache And Display Entries

We want to use IDB to store the wittr messages. The logic is when the page start: service worker will read the skeleton from the cache and show to the interface. read the message data from the IDB first instead of going to network. Show the data from

[PWA] 11. Serve skeleton cache for root

Intead of cache the root floder, we want to cache skeleton instead. self.addEventListener('install', function (event) { event.waitUntil( caches.open(staticCacheName).then(function (cache) { return cache.addAll([ '/skeleton', 'js/main.js', 'css/main.c

[PWA] 19. Cache the avatars

Cache the avatars is little different from cache photos. We need to serve the page with our cache data and also go to the network for fetch avatars in case some user like change their avatars frequently. self.addEventListener('fetch', function(event)

[PWA] 18. Clean the photo cache

We cannot let photo always keep caching new data without clean the old data. If message is not display on the page anymore, we want to clean it. And also every 5 mins we want to clean the photo data. export default function IndexController(container)

[PWA] 17. Cache the photo

To cache photo, You need to spreate cache db to save the photo. So in wittr example, we cache the text already, if there in the wittr there is photo, we will create cache for it, so next time we can fetch from cache. For the incoming photo, we also n