violet0sea / note

can not open gist, so write here
0 stars 0 forks source link

PWAS #15

Open violet0sea opened 6 years ago

violet0sea commented 6 years ago

注册,首先需要进行特性检查 if('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('/sw.js').then(function(registeration) { // do sth succ }).catch(function(err) { // dosth err }) }); }

每次加载页面时浏览器会判断是否已经注册

安装事件 self.addEventListener('install'), function(event) { // open cache // cache file const CACHE_NAME = 'my_site_cache_v1'; cosnt urlsToCache = [ '/', './idnex.html', './main.css', './main.jss' ]; event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('cahes are open'); return cache.addAll(urlsToCache); }) ); });

所有文件都缓存成功时,才回去安装服务工作线程,任何文件缓存失败都将导致安装步骤失败,然而更多的情况是想缓存请求

监听fetch事件 `self.addEventListener('fetch',. function(event) { event.respondWith( caches.match(event.request) .then(function(response) { if(response) { return response; } return fetch(event.request); }) ) })