您的位置:首页 > Web前端 > HTML5

Service Worker 缓存技术

2017-12-27 15:04 281 查看
一、关于H5缓存技术

提到H5缓存我们应该会想到应用缓存(application cache),只需要在标签上加一个配置
<html menifest='index.appcache'>
,然后编辑对应的index.appcache,就能实现我们的缓存。

CACHE MANIFEST
# v1
CACHE:
index.html
cache.html
style.css
image1.png

# Use from network if available
NETWORK:
network.html

# Fallback content
FALLBACK:
/ fallback.html


使用应用缓存(application cache) — MDN

但是,



二、使用Service Worker实现缓存

Service_Worker_API

ServiceWorker文档

1>什么是service worker?

service worker也称服务器工作线程,是浏览器在后台独立网页运行的脚本。我们平常浏览器窗口中跑的页面运行的是主JavaScript线程,DOM和window全局变量都是可以访问的。而Service Worker是走的另外的线程,可以理解为在浏览器背后默默运行的一个线程,脱离浏览器窗体,因此,window以及DOM都是不能访问的,此时我们可以使用self访问全局上下文。

2>兼容性

请查看https://caniuse.com/#feat=serviceworkers

3>使用前提

使用service worker,传输协议必须为HTTPS。因为service worker中涉及到请求拦截,所以必须使用HTTPS协议来保障安全。如果是本地调试的话,localhost是可以的。

4> service worker的生命周期



①注册(register)当你的应用未注册过service worker,那么第一步就是注册;

②安装(install),注册完成之后,会触发install,在这一步我们可以进行文件缓存;

③响应请求(fetch),fetch用于拦截用户请求,并响应,返回Promise对象,成功安装service worker后,待用户下次再进入页面,返回已返回的文件。

④更新(activate),当网站上当前页面被关闭,旧服务线程被终止。重新打开网页时,新服务工作线程取得控制权后,会触发activate事件。这一步我们可以清楚就版本缓存。

5>使用

页面中引用的js文件

进行service worker 注册

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' }).then(function(reg) {

if(reg.installing) {
console.log('Service worker installing');
} else if(reg.waiting) {
console.log('Service worker installed');
} else if(reg.active) {
console.log('Service worker active');
}

}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
}


service worker文件,sw.js

var VERSION = 'v1';//一个存储空间

// 缓存
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(VERSION).then(function(cache) {
return cache.addAll([//需要缓存的文件
'/sw-test/',
'/sw-test/index.html',
'/sw-test/style.css',
'/sw-test/app.js',
'/sw-test/image-list.js',
'/sw-test/star-wars-logo.jpg',
'/sw-test/gallery/bountyHunters.jpg',
'/sw-test/gallery/myLittleVader.jpg',
'/sw-test/gallery/snowTroopers.jpg'
]);
})
);
});

// 缓存更新
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
// 如果当前版本和缓存版本不一致
if (cacheName !== VERSION) {
return caches.delete(cacheName);
}
})
);
})
);
});

// 捕获请求并返回缓存数据
self.addEventListener('fetch', function(event) {
event.respondWith(caches.match(event.request).catch(function() {
return fetch(event.request);
}).then(function(response) {
caches.open(VERSION).then(function(cache) {
cache.put(event.request, response);
});
return response.clone();
}).catch(function() {
return caches.match('/sw-test/gallery/myLittleVader.jpg');
}));
});


运行demo: https://mdn.github.io/sw-test/
打开浏览器查看(请使用隐身模式):

选择offline 页面依旧显示正常

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  缓存 h5