Created
May 4, 2018 08:32
-
-
Save giscafer/a873fddf6e892a8a1efd34e7e14178d1 to your computer and use it in GitHub Desktop.
service worker demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // download & parse | |
| if ('serviceWorker' in navigator) { | |
| navigator.serviceWorker.register('./sw.js?' + new Date().getTime()).then(function(registration) { | |
| // 注册成功 | |
| console.log('ServiceWorker registration successful with scope:' + registration.scope); | |
| }).catch(function(err) { | |
| // 注册失败1 | |
| console.log('ServiceWorker registration failed:', err); | |
| }); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 事件监听 | |
| //通过使用 skipWaiting() 函数,最终会触发 activate 事件,并告知 Service Worker 立即开始工作,而无需等待用户跳转或刷新页面 | |
| self.addEventListener('install', function(event) { | |
| console.info('install') | |
| event.waitUntil(self.skipWaiting()); | |
| }); | |
| //确保底层 Service Worker 的更新立即生效 | |
| self.addEventListener('activate', function(event) { | |
| console.info('activate') | |
| event.waitUntil(self.clients.claim()); | |
| }); | |
| // 拦截所有请求 | |
| self.addEventListener('fetch', function(event) { | |
| console.log(event.request.url); | |
| // 更改png图片 | |
| if (/\.png$/.test(event.request.url)) { | |
| // event.respondWith(fetch('http://www.easyicon.net/api/resizeApi.php?id=1204391&size=128', { mode: 'no-cors' })); | |
| // event.respondWith(fetch('./assets/img/logo.png')); | |
| /* event.respondWith( | |
| new Response('<p>This is a response that comes from your service worker!</p>', { | |
| headers: { 'Content-Type': 'text/html' } | |
| }) | |
| ); */ | |
| } | |
| // Save-Data | |
| if (event.request.headers.get('save-data')) { | |
| // 我们想要节省数据,所以限制了图标和字体 | |
| if (event.request.url.includes('fonts.googleapis.com')) { | |
| // 不返回任何内容 | |
| event.respondWith(new Response('', { status: 417, statusText: 'Ignore fonts to save data.' })); | |
| } | |
| } | |
| //缓存文件 | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment