-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmip-sw.js
More file actions
78 lines (71 loc) · 2.43 KB
/
mip-sw.js
File metadata and controls
78 lines (71 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* @file mip serviceworker processor
* @author mj(zoumiaojiang@gmail.com)
*/
/* global self, caches, fetch */
var CACHE_NAME = 'mip-sw-static-cache'
self.MIP_SW_VERSION = '__BUILD_TIME__'
self.MIP_SW_TAG = '__BUILD_TAG__'
self.addEventListener('install', function () {
self.skipWaiting()
})
// self.addEventListener('activsate', function (event) {
// event.waitUntil(
// caches.keys().then(function (keys) {
// return Promise.all(
// keys.map(function (key) {
// if ([CACHE_NAME].includes(key)) {
// return caches.delete(key)
// }
// })
// )
// }).then(function () {
// return self.clients.matchAll()
// .then(function (clients) {
// clients && clients.length && clients.forEach(function (client) {
// client.postMessage('sw.update')
// })
// })
// })
// )
// })
self.addEventListener('fetch', function (event) {
var url = new URL(event.request.url)
var netLevel = 0
var connection = navigator.connection ||
navigator.mozConnection ||
navigator.webkitConnection ||
navigator.msConnection
var matchReg = /https?:\/\/(c\.mipcdn|mipcache\.bdstatic)\.com\/(static|extensions\/platform)\//
var jetMatchReg = /https?:\/\/(jet\.bdstatic|c\.mipcdn)\.com\/byurl\?/
// var mipPageReg = /https?:\/\/.*\.mipcdn\.com\/[cir]\/|http:\/\/localhost/
var mipSwReg = /mip-sw-.*\.js|mip\.js|mip\.css/
// @todo:网络策略以及兼容性有待调整
if (connection) {
if (connection.effectiveType) {
netLevel = connection.effectiveType.toUpperCase() === '4G' ? 0 : 1
} else if (connection.type) {
netLevel = connection.type.toUpperCase() === 'WIFI' ? 0 : 1
}
}
/**
* 弱网情况下才引入 service worker fetch 代理
* 只是缓存 MIP 核心 JS 和 MIP 官方组件以及平台组件以及 JET 静态资源(@todo:策略待调整)
*/
if (netLevel > 0 &&
(matchReg.test(url) || jetMatchReg.test(url) /* || mipPageReg.test(url) */) &&
!mipSwReg.test(url)
) {
event.respondWith(
caches.open(CACHE_NAME).then(function (cache) {
return cache.match(event.request).then(function (response) {
var fetchPromise = fetch(event.request).then(function (networkResponse) {
cache.put(event.request, networkResponse.clone())
return networkResponse
})
return response || fetchPromise
})
})
)
}
})