[JavaScript] 纯文本查看 复制代码
<!-- 把3种资源都改成请求两次 -->
<link rel="stylesheet" href="/static/index.css">
<link rel="stylesheet" href="/static/index.css">
<script src="/static/index.js"></script>
<script src="/static/index.js"></script>
<img src="/static/mashroom.jpg">
<img src="/static/mashroom.jpg">
<!-- 异步请求图片 -->
<script>
setTimeout(function () {
let img = document.createElement('img')
img.src = '/static/mashroom.jpg'
document.body.appendChild(img)
}, 1000)
</script>
[JavaScript] 纯文本查看 复制代码
// serviceWorker.js
self.addEventListener('install', e => {
// 当确定要访问某些资源时,提前请求并添加到缓存中。
// 这个模式叫做“预缓存”
e.waitUntil(
caches.open('service-worker-test-precache').then(cache => {
return cache.addAll(['/static/index.js', '/static/index.css', '/static/mashroom.jpg'])
})
)
})
self.addEventListener('fetch', e => {
// 缓存中能找到就返回,找不到就网络请求,之后再写入缓存并返回。
// 这个称为 CacheFirst 的缓存策略。
return e.respondWith(
caches.open('service-worker-test-precache').then(cache => {
return cache.match(e.request).then(matchedResponse => {
return matchedResponse || fetch(e.request).then(fetchedResponse => {
cache.put(e.request, fetchedResponse.clone())
return fetchedResponse
})
})
})
)
})