-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebAppCache.js
539 lines (451 loc) · 15.2 KB
/
WebAppCache.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/**
* WebAppCache v1.0.3
* 2013, zawa, www.zawaliang.com
* Licensed under the MIT license.
*/
;(function(window, document, undefined) {
var _local = localStorage,
_session = sessionStorage,
_pathname = location.pathname,
_appName = _pathname, // App标识
_fireQueue = [], // 最终需要执行的队列
_onload = false,
_renderReady = false,
_cache = {},
_storage = null,
_viewName = getParam('v');
function getParam(name) {
var p = '&' + location.search.substr(1) + '&',
re = new RegExp('&' + name + '=([^&]*)&'),
r = p.match(re);
return r ? r[1] : '';
}
function get(url, callback, errorHandler) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var status = xhr.status;
if ((status >= 200 && status < 300) || status == 304) {
callback.call(null, xhr.responseText);
} else {
var msg = status ? 'Error:' + status : 'Abort';
(getType(errorHandler) == 'function')
? errorHandler(status, msg)
: null;
}
}
};
// xhr.withCredentials = true;
xhr.open('get', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(null);
}
/**
* 数据类型
* @param {*} o
* @return {String} string|array|object|function|number|boolean|null|undefined
*/
function getType(o) {
var t = typeof(o);
return (t == 'object' ? Object.prototype.toString.call(o).slice(8, -1) : t).toLowerCase();
}
function each(item, callback) {
if (getType(item) == 'array') {
for (var i = 0, len = item.length; i < len; i++) {
callback.apply(null, [i, item[i]]);
}
} else {
for (var k in item) {
if (item.hasOwnProperty(k)) {
callback.apply(null, [k, item[k]]);
}
}
}
}
function inArray(item, arr) {
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i] === item) {
return i;
}
};
return -1;
}
/**
* 优化的缓存设置, 溢出捕获以及队列管理
*/
function cache(n, v, prefix) {
prefix = (getType(prefix) == 'string') ? prefix : _appName;
if (getType(v) == 'undefined') {
var r = _storage.getItem(prefix + n);
if (r === null) {
return null;
}
try {
return JSON.parse(r);
} catch (e) {
return r;
}
}
// 缓存当前应用的写操作key值(无序)
if (prefix == _appName) {
var cacheKey = cache('CacheKey') || [];
cacheKey.push(n);
cacheKey = uniq(cacheKey);
_storage.setItem(_appName + 'CacheKey', JSON.stringify(cacheKey));
}
if (getType(v) != 'string') {
v = JSON.stringify(v);
}
try {
_storage.setItem(prefix + n, v);
} catch (e) {
var appName = shiftAppCache();
if (appName !== false) { // 重新尝试缓存
cache(n, v);
} else { // 没有应用缓存可供删除时, 淘汰当前应用队列
var cq = cache('Core') || [],
sq = sourceQueue();
// 将Core与Source资源合并进行队列管理
sq = sq.concat(cq);
// 缓存区不足时,淘汰当前应用缓存重新发起请求
if (sq.length < 1) {
clearAppCache(_appName);
location.reload(false);
return;
}
var item = sq.shift(),
key = _appName + item;
// 删除最早的缓存
_storage.removeItem(key);
_storage.removeItem(key + '.Version');
// 更新队列
sourceQueue(sq);
// 重新尝试缓存
cache(n, v);
}
}
}
/**
* 清空应用缓存
*/
function clearAppCache(appName) {
var cacheKey = cache('CacheKey', undefined, appName) || [];
each(cacheKey, function(k, v) {
_storage.removeItem(appName + v);
});
_storage.removeItem(appName + 'CacheKey');
}
/**
* 按应用缓存队列清空应用缓存(跳过当前应用缓存)
*/
function shiftAppCache() {
var appQueue = cache('App.Queue', undefined, '') || [];
appQueue = arrDel(_appName, appQueue); // 跳过当前应用缓存
if (appQueue.length > 0) {
var appName = appQueue.shift();
clearAppCache(appName);
cache('App.Queue', appQueue, '');
return appName
}
return false;
}
/**
* 缓存非核心资源队列
*/
function sourceQueue(sq) {
return (getType(sq) != 'undefined')
? cache('Source', sq)
: cache('Source') || [];
}
/**
* 格式化配置
*/
function formatAppConf(conf) {
var source = {};
each(['js', 'css', 'page'], function(k, v) {
conf[v] && each(conf[v], function(k2, v2) {
var name = v + '_' + k2;
v2.__name__ = k2;
v2.__type__ = v;
v2.v = v2.v || ''; // 版本号缺省为空
source[name] = v2;
});
// 删除格式化后的js css page配置
conf[v] = null;
delete conf[v];
});
conf.__source__ = source;
return conf;
}
function concatArr(arr, type) {
each(arr, function(k, v) {
arr[k] = type + v;
});
return arr;
}
/**
* 删除数组某项
*/
function arrDel(n, arr) {
var i = inArray(n, arr);
if (i != -1) {
arr.splice(i, 1);
}
return arr;
}
/**
* 去重
*/
function uniq(arr) {
var hash = {},
r = [];
each(arr, function(k, v) {
if (!hash[v]) {
r.push(v);
hash[v] = 1;
}
});
return r;
}
/**
* 队列去重与依赖处理
*/
function handleFireQueue(config) {
var view = 'page_' + _viewName, // 加载的视图
source = config.__source__,
view = source[view] ? view : 'page_index',
c = source[view] || {},
jsCore = config.jsCore || [],
cssCore = config.cssCore || [],
jsQueue = jsCore.concat(c.js || []),
cssQueue = cssCore.concat(c.css || []);
jsQueue = concatArr(jsQueue, 'js_');
cssQueue = concatArr(cssQueue, 'css_');
// 去重
jsQueue = uniq(jsQueue);
cssQueue = uniq(cssQueue);
// TODO: 依赖管理(暂时按数组顺序加载)
// 保持css队列在前, 提升后续开始加载时间
_fireQueue = cssQueue.concat(jsQueue);
_fireQueue.push(view);
}
/**
* 获取资源路径
*/
function getPath(config, c) {
if (c.url) {
return c.url;
}
var conf = config[c.__type__ + 'Config'] || {};
return conf.path + c.__name__.replace(/\./g, '/') + conf.suffix;
}
/**
* 更新队列
*/
function updateQueue(queue) {
var config = _cache['Config'],
source = config.__source__,
cq = cache('Core') || [],
sq = sourceQueue(),
len = queue.length,
loaded = 0;
// 并行加载资源
each(queue, function(k, v) {
var s = source[v],
path = getPath(config, s),
url = path + '?_=' + (s.v == -1 ? (+new Date()) : s.v);
get(url, (function(n, c) {
return function(data) {
// 1) 核心资源不计入Source队列
// 2) 非缓存资源不计入Source队列
if (inArray(n, cq) == -1 && c.v != -1) {
// 若缓存中已存在n的资源,则更新其队列位置
if (inArray(n, sq) != -1) {
sq = arrDel(n, sq);
}
sq.push(n);
}
// 缓存时方存储
if (c.v != -1) {
cache(n, data);
cache(n + '.Version', c.v);
}
_cache[n] = data;
loaded++;
if (loaded == len) {
// 按添加时间缓存队列
sourceQueue(sq);
render();
}
};
})(v, s));
});
}
/**
* 版本比较
*/
function cmpVersion(config) {
var source = config.__source__,
jsCore = config.jsCore || [],
cssCore = config.cssCore || [];
handleFireQueue(config);
// 缓存核心资源队列(按依赖权重升序排列,css在前,js在后, 用于缓存队列管理)
var core = [];
core[0] = concatArr(cssCore, 'css_').reverse();
core[1] = concatArr(jsCore, 'js_').reverse();
core = core[0].concat(core[1]);
cache('Core', core);
// 检查资源是否需要更新
var udQueue = [];
each(_fireQueue, function(k, v) {
_cache[v] = cache(v);
if (source[v].v == -1 // 不需缓存
|| _cache[v] === null // 本地不存在v的缓存
|| cache(v + '.Version') != source[v].v // 有新版本
) {
udQueue.push(v);
}
});
if (udQueue.length > 0) { // 有更新队列
updateQueue(udQueue);
} else { // 版本没变化
render();
}
}
// http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/
// http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#dom-script-text
var appendJs = function(text) {
var body = document.getElementsByTagName('body')[0],
script = document.createElement('script');
script.type = 'text/javascript';
// script.charset = 'utf-8';
script.defer = 'true';
script.text = text;
body.appendChild(script); // 插入到body下,防止defer不支持造成js于DOM加载完成前触发
};
/**
* 检查是否可渲染
*/
function render() {
_renderReady = true;
if (_onload) {
goRender();
}
}
/**
* 页面渲染
*/
function goRender() {
var config = _cache['Config'],
source = config.__source__ || {},
arrText = {};
each(_fireQueue, function(k, v) {
var type = source[v].__type__;
if (!arrText[type]) {
arrText[type] = [];
}
arrText[type].push(_cache[v] || '');
});
var page = arrText.page.join('');
// css优先于页面其他样式渲染
var css = '<style type="text/css">' + arrText.css.join('\n') + '<\/style>\n',
hp = page.indexOf('</head>'),
match = page.match(/<style(?:\s.*)?>/),
p = match ? Math.min(page.indexOf(match[0]), hp) : hp;
page = page.substr(0, p) + css + page.substr(p);
// 写入文档流
document.open('text/html', 'replace'); // replace: 新建的文档会覆盖当前页面的文档(清空原文档里的所有元素,浏览器的后退按钮不可用);
document.write(page);
// js
arrText.js = arrText.js.join(';');
appendJs(arrText.js);
// bugfix: 修复微信5.0以下版本要刷新才会触发JS的问题, 这里将document.close后置到appendJS后
// 或者不显式调用document.close
document.close();
arrText = page = js = css = null;
// 清空标记位
_onload = _renderReady = false;
}
/**
* 离线处理
*/
function onOffLine(config) {
var cacheMatch = 0;
handleFireQueue(config);
// 获取本地缓存
each(_fireQueue, function(k, v) {
_cache[v] = cache(v);
// 缓存是否命中
if (_cache[v] !== null) {
cacheMatch++;
}
});
if (cacheMatch == _fireQueue.length) {
render();
} else {
document.write(config.networkError);
}
}
function init() {
var localStorageEnabled = false;
if (!!_local) {
// 检测webview是否开启localStorage
var key = _appName + 'CacheEnabled';
_local.setItem(key, 1);
localStorageEnabled = (_local.getItem(key) == 1);
localStorageEnabled && _local.removeItem(key);
}
// 缓存,不支持localStorage的使用sessionStorage替代,此时使用304缓存方案
_storage = localStorageEnabled ? _local : _session
// 缓存App队列,方便溢出时管理
var appQueue = cache('App.Queue', undefined, '') || [];
// 按使用时间更新App队列顺序
if (inArray(_appName, appQueue) != -1) {
appQueue = arrDel(_appName, appQueue);
}
appQueue.push(_appName);
cache('App.Queue', appQueue, '');
// App.Config有效期检查
var config = cache('Config'),
expire = cache('Config.Expire'),
updateConfig = false;
_cache['Config'] = config;
// 离线情况下,直接渲染输出
if (!navigator.onLine) {
onOffLine(config);
return;
}
if (config && expire) {
var now = +new Date();
if ((now - expire.time) / (1000 * 60) > expire.expire) {
updateConfig = true;
}
} else {
updateConfig = true;
}
if (updateConfig) {
var path = _pathname.substring(0, _pathname.lastIndexOf('/')+1),
jsonFile = path + 'app.json';
get(jsonFile + '?_=' + (+new Date()), function(data) {
data = formatAppConf(JSON.parse(data));
cache('Config', data);
cache('Config.Expire', {
time: +new Date(),
expire: data.expire
});
_cache['Config'] = data;
cmpVersion(data);
});
} else {
cmpVersion(config);
}
}
// document.write在window.onload(非DOMContentLoaded)完毕后方可覆盖原文档
window.addEventListener('load', function() {
_onload = true;
if (_renderReady) {
goRender();
}
});
init();
})(window, document);