iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 16
3
Modern Web

30 天 Progressive Web App 學習筆記系列 第 16

Day 16 - 30 天 Progressive Web App 學習筆記 - Service Worker - Clearing Old Cache

為什麼要清除 Old Cache?

前面的文章有講到,我們會去 註冊 Service Worker ,接著在 install 的事件裡進行 Pre-cache assets。

const filesToCache = [
	'/',
	'/index.html'
];
const cacheName = 'static-v1';

// install
self.addEventListener('install', event => {
	console.log('installing…');
	event.waitUntil(
		caches.open(cacheName).then(cache => {
			console.log('Caching app ok');
			return cache.addAll(filesToCache);
		})
	);
}); 

成功 Cache Assets 之後,再進入 fetch 事件、攔截 Fetch Requests 並將 response 存入 Cache。

接著會遇到一個問題:發現 Fetch 到的資料會一直被 Cache 住,不會自動更新,所以我們必須清除舊的 Cache。


如何清除舊的 Cache?

Service Worker 有一個 activate 事件,會去 handle fetches。
程式碼執行如下:

// activate
self.addEventListener('activate', event => {
	console.log('now ready to handle fetches!');
	  event.waitUntil(
		caches.keys().then(function(cacheNames) {
			var promiseArr = cacheNames.map(function(item) {
				if (item !== cacheName) {
					// Delete that cached file
					return caches.delete(item);
				}
			})
			return Promise.all(promiseArr);
		})
	); // end e.waitUntil
});

進到 activate 事件之後,一定要執行 event.waitUntil(); ,這個方法會等 caches.keys().then 執行結束後 activate 的 event 才會真的結束。

caches.keys() 是 caches 的 API,負責的工作是把所有的 cacheName 取出來,回傳的 cacheNames 是個 Array,是一個 Array、裡面的元素是 String,例如:cacheName 會是 ['static-v1', 'static-v1-api']

接著 cacheNames.map 產生 Array,map 出來的 item 去判斷 是不是等於 cacheName,如果不等於就刪除 cached 檔案。

Promise.all 的意思是等到 promiseArr 這個陣列所有的 promise 物件結束後,才可以繼續執行回傳的動作。

最後只要 fetch 資料發生改變,就會觸發 activate 事件,並刪除舊的 Cache,接著取得新的 fetch 資料,畫面上的資料就會是最新的摟~ :D


本人小小筆記,如有錯誤或需要改進的部分,歡迎給予回饋。
我將會用最快的速度修正,m(_ _)m。謝謝

上一篇
Day 15 - 30 天 Progressive Web App 學習筆記 - Service Worker - Setting up the Default Cache
下一篇
Day 17 - 30 天 Progressive Web App 學習筆記 - Service Worker - Handling Fetch Requests
系列文
30 天 Progressive Web App 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
lovero32000
iT邦新手 5 級 ‧ 2018-03-02 14:21:58

接著 cacheNames.map 產生 Array,map 出來的 item 去判斷 是不是等於 cacheName,如果不等於就刪除 cached 檔案。

const cacheName = 'static-v1';

caches.keys().then(function(cacheNames) {
    var promiseArr = cacheNames.map(function(item) {
        if (item !== cacheName) {
            // Delete that cached file
            return caches.delete(item);
        }
    })
    return Promise.all(promiseArr);
})

請問這段, 這樣不就會刪除到不屬於自己的cache嗎?

還是我有理解有誤

不好意思, 在看那麼久以前的文章

我要留言

立即登入留言