-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.js
108 lines (84 loc) · 2.42 KB
/
index.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
/**
* @file hexo-pwa entry
* @author pengxing([email protected])
*/
'use strict';
/* globals hexo */
const fs = require('fs');
const path = require('path');
const tpl = require('lodash.template');
const manifestGenerator = require('./lib/manifest');
const serviceWorkerGenerator = require('./lib/serviceWorker');
let compiledSWRegTpl;
let asyncLoadPageJSTpl;
if (hexo.config.pwa.manifest) {
// generate manifest json file
hexo.extend.generator.register('manifest', manifestGenerator);
}
if (hexo.config.pwa.serviceWorker) {
// get sw register code and compile
let swTpl = fs.readFileSync(path.resolve(__dirname, './templates/swRegister.tpl.js'));
compiledSWRegTpl = tpl(swTpl)({path: hexo.config.pwa.serviceWorker.path + '?t=' + Date.now()});
// generate service worker file
hexo.extend.generator.register('serviceWorker', serviceWorkerGenerator);
}
if (hexo.config.pwa.asyncLoadPage) {
// get async load page js tpl
asyncLoadPageJSTpl = fs.readFileSync(path.resolve(__dirname, './templates/asyncLoadPage.tpl.js'));
}
// inject manifest into html files
hexo.extend.filter.register('after_render:html', data => {
if (!data) {
return;
}
// inject code into pages
if (hexo.config.pwa.manifest) {
data = injectManifest(data);
}
if (hexo.config.pwa.serviceWorker) {
data = injectSWRegister(data);
}
if (hexo.config.pwa.asyncLoadPage) {
data = injectAsyncLoadPageJS(data);
}
return data;
}, hexo.config.pwa.priority || 10);
/**
* inject manifest html fragment into page code
*
* @param {string} data html
* @return {string}
*/
function injectManifest(data) {
let manifestHtml = `<head><link rel=manifest href=${hexo.config.pwa.manifest.path}>`;
if (data.indexOf(manifestHtml) === -1) {
data = data.replace('<head>', manifestHtml);
}
return data;
}
/**
* inject service worker registion fragment into page code
*
* @param {string} data html
* @return {string}
*/
function injectSWRegister(data) {
let swHtml = `<script>${compiledSWRegTpl}</script></body>`;
if (data.indexOf(compiledSWRegTpl) === -1) {
data = data.replace('</body>', swHtml);
}
return data;
}
/**
* inject async load page js fragment
*
* @param {string} data html
* @return {string}
*/
function injectAsyncLoadPageJS(data) {
let injectHtml = `<script>${asyncLoadPageJSTpl}</script>`;
if (data.indexOf(injectHtml) === -1) {
data = data.replace('</head>', injectHtml);
}
return data;
}