Authored by 毕凯

代码整理

... ... @@ -8,7 +8,7 @@ let baseConfig = require('./webpack.base.config.js');
baseConfig = baseConfig('dev');
// https 环境不支持自动刷新
if (!devInfo.publicPath.indexOf('https')) {
if (devInfo.publicPath.indexOf('https')) {
const path = require('path');
Object.keys(baseConfig.entry).forEach(function(name) {
... ...
... ... @@ -2,10 +2,10 @@ const usePwa = true;
window.addEventListener('load', function() {
if ('serviceWorker' in navigator) {
const t = window.STATIC_RESOURCE_HASH || '';
const staticServer = window.STATIC_RESOURCE_PATH || '';
if (usePwa) {
const t = window.STATIC_RESOURCE_HASH || '';
const staticServer = window.STATIC_RESOURCE_PATH || '';
navigator.serviceWorker.register(`/sw.js?t=${t}&staticServer=${staticServer}`, {
scope: '/'
}).then(function(registration) {
... ...
/* eslint-env worker */
importScripts('https://cdn.yoho.cn/pwa/workbox-sw.prod.v2.1.2.js');
// 不得已写 es5 的代码,忽略 var
/* eslint-disable vars-on-top */
var precacheStaticFile = [
'/index.css',
'/common.css',
'/libs.js',
'/channel.index.js'
];
var customCacheDomain = [
'cdn.yoho.cn',
'static.yhbimg.com'
];
// 工具函数
function iSInCustomCacheDomain(domain) {
var isIn = false;
customCacheDomain.forEach(function(d) {
if (domain.indexOf(d) >= 0) {
isIn = true;
}
});
return isIn;
}
var config = {
customCacheDomain: [
'cdn.yoho.cn',
'static.yhbimg.com'
],
precacheStaticFile: [
'/index.css',
'/common.css',
'/libs.js'
],
precacheFile: [{
url: 'https://cdn.yoho.cn/pwa/workbox-sw.prod.v2.1.2.js'
}]
};
var utils = {
iSInCustomCacheDomain: function(domain) {
var isIn = false;
config.customCacheDomain.forEach(function(d) {
if (domain.indexOf(d) >= 0) {
isIn = true;
}
});
return isIn;
},
function parseQs(str) {
var vars = {},
hashes,
hash,
i;
parseQs: function(str) {
var vars = {},
hashes,
hash,
i;
str = str || '';
str = str || '';
if (str) {
hashes = str.split('&');
for (i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars[hash[0]] = hash[1];
if (str) {
hashes = str.split('&');
for (i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars[hash[0]] = hash[1];
}
}
return vars;
}
return vars;
}
};
var qs = utils.parseQs(self.location.search.substr(1));
var workboxSW;
var qs = parseQs(self.location.search.substr(1));
// 加载 workbox,后边看下怎么好好利用
importScripts('https://cdn.yoho.cn/pwa/workbox-sw.prod.v2.1.2.js');
// WorkboxSW
var workboxSW = new self.WorkboxSW({
workboxSW = new self.WorkboxSW({
clientsClaim: true,
skipWaiting: true
});
var precacheFile = [
{
url: '/sw.js?t=' + qs.t + '&staticServer=' + qs.staticServer
},
{
url: 'https://cdn.yoho.cn/pwa/workbox-sw.prod.v2.1.2.js'
},
{
url: '/'
}
];
precacheFile = precacheFile.concat(precacheStaticFile.map(function(file) {
// 特殊路径的预缓存文件文件
config.precacheFile = config.precacheFile.concat([{
url: '/sw.js?t=' + qs.t + '&staticServer=' + qs.staticServer
}]).concat(config.precacheStaticFile.map(function(file) {
// 根据业务自定义资源路径
var url = self.location.protocol + qs.staticServer + file + '?t=' + qs.t;
... ... @@ -73,17 +68,21 @@ precacheFile = precacheFile.concat(precacheStaticFile.map(function(file) {
};
}));
workboxSW.precache(precacheFile);
// 初始化
workboxSW.precache(config.precacheFile);
// self.addEventListener('install', function(event) {
// event.waitUntil(
// caches.open('common-cache').then(function(cache) {
// return cache.addAll([
// 'https://devcdn.yoho.cn:7001/index.css'
// ]);
// })
// );
// });
self.addEventListener('install', function(event) {
console.log('install', event);
// event.waitUntil(
// caches.open('common-cache').then(function(cache) {
// return cache.addAll([
// '/'
// ]);
// })
// );
});
self.addEventListener('error', event => {
console.error('error', event);
... ... @@ -96,6 +95,7 @@ self.addEventListener('error', event => {
// event.colno
// event.error.stack
});
self.addEventListener('unhandledrejection', event => {
console.error('unhandledrejection', event);
... ... @@ -106,41 +106,41 @@ self.addEventListener('unhandledrejection', event => {
self.addEventListener('fetch', function(event) {
var domain = event.request.url.split('/')[2];
var shouldCache = iSInCustomCacheDomain(domain);
var shouldCache = utils.iSInCustomCacheDomain(domain);
// 使用域名白名单进行缓存
if (shouldCache) {
event.respondWith(
caches.match(event.request).then(function(response) {
var request = event.request.clone(); // 把原始请求拷过来
// 如果 Service Worker 有自己的返回,就直接返回,减少一次 http 请求
if (response) {
return response;
}
// 如果 service worker 没有返回,那就得直接请求真实远程服务
let request = event.request.clone(); // 把原始请求拷过来
return fetch(request, {
mode: 'cors',
credentials: 'same-origin'
}).then(function(httpRes) {
var httpResClone = httpRes.clone();
// 请求失败了,直接返回失败的结果就好了。。
if (!httpRes || httpRes.status !== 200) {
return httpRes;
}
// 请求成功的话,将请求缓存起来。
var responseClone = httpRes.clone();
caches.open('custom-cache').then(function(cache) {
cache.put(event.request, responseClone);
cache.put(event.request, httpResClone);
});
return httpRes;
}).catch(console.error);
});
}).catch(function(err) {
console.log(err);
})
);
}
});
/* eslint-enable vars-on-top */
... ...