Skip to content

Commit e716b59

Browse files
committed
minify js, css in html
1 parent 51f86bb commit e716b59

3 files changed

Lines changed: 163 additions & 5 deletions

File tree

‎app/index.html‎

Lines changed: 130 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,136 @@
1919
<div class="app"></div>
2020
<script src="./js/app.js"></script>
2121
<script>
22-
var frame = document.createElement('iframe');
23-
frame.style.display = "none";
24-
frame.src = 'sw.html?' + Date.now();
25-
document.body.appendChild(frame);
22+
if (/https/.test(location.protocol) && 'serviceWorker' in navigator) {
23+
if (!Cache.prototype.add) {
24+
Cache.prototype.add = function add(request) {
25+
return this.addAll([request]);
26+
};
27+
}
28+
29+
if (!Cache.prototype.addAll) {
30+
Cache.prototype.addAll = function addAll(requests) {
31+
var cache = this;
32+
33+
// Since DOMExceptions are not constructable:
34+
function NetworkError(message) {
35+
this.name = 'NetworkError';
36+
this.code = 19;
37+
this.message = message;
38+
}
39+
NetworkError.prototype = Object.create(Error.prototype);
40+
41+
return Promise.resolve().then(function() {
42+
if (arguments.length < 1) throw new TypeError();
43+
44+
// Simulate sequence<(Request or USVString)> binding:
45+
var sequence = [];
46+
47+
requests = requests.map(function(request) {
48+
if (request instanceof Request) {
49+
return request;
50+
}
51+
else {
52+
return String(request); // may throw TypeError
53+
}
54+
});
55+
56+
return Promise.all(
57+
requests.map(function(request) {
58+
if (typeof request === 'string') {
59+
request = new Request(request);
60+
}
61+
62+
var scheme = new URL(request.url).protocol;
63+
64+
if (scheme !== 'http:' && scheme !== 'https:') {
65+
throw new NetworkError("Invalid scheme");
66+
}
67+
68+
return fetch(request.clone());
69+
})
70+
);
71+
}).then(function(responses) {
72+
// TODO: check that requests don't overwrite one another
73+
// (don't think this is possible to polyfill due to opaque responses)
74+
return Promise.all(
75+
responses.map(function(response, i) {
76+
return cache.put(requests[i], response);
77+
})
78+
);
79+
}).then(function() {
80+
return undefined;
81+
});
82+
};
83+
}
84+
85+
if (!CacheStorage.prototype.match) {
86+
// This is probably vulnerable to race conditions (removing caches etc)
87+
CacheStorage.prototype.match = function match(request, opts) {
88+
var caches = this;
89+
90+
return this.keys().then(function(cacheNames) {
91+
var match;
92+
93+
return cacheNames.reduce(function(chain, cacheName) {
94+
return chain.then(function() {
95+
return match || caches.open(cacheName).then(function(cache) {
96+
return cache.match(request, opts);
97+
}).then(function(response) {
98+
match = response;
99+
return match;
100+
});
101+
});
102+
}, Promise.resolve());
103+
});
104+
};
105+
}
106+
107+
if ('serviceWorker' in navigator) {
108+
// Delay registration until after the page has loaded, to ensure that our
109+
// precaching requests don't degrade the first visit experience.
110+
// See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration
111+
window.addEventListener('load', function() {
112+
// Your service-worker.js *must* be located at the top-level directory relative to your site.
113+
// It won't be able to control pages unless it's located at the same level or higher than them.
114+
// *Don't* register service worker file in, e.g., a scripts/ sub-directory!
115+
// See https://github.com/slightlyoff/ServiceWorker/issues/468
116+
navigator.serviceWorker.register('sw.js').then(function(reg) {
117+
setInterval(reg.update, 60 * 60 * 1000); // update the service worker hourly
118+
// updatefound is fired if service-worker.js changes.
119+
reg.onupdatefound = function() {
120+
// The updatefound event implies that reg.installing is set; see
121+
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
122+
var installingWorker = reg.installing;
123+
124+
installingWorker.onstatechange = function() {
125+
switch (installingWorker.state) {
126+
case 'installed':
127+
if (navigator.serviceWorker.controller) {
128+
// At this point, the old content will have been purged and the fresh content will
129+
// have been added to the cache.
130+
// It's the perfect time to display a "New content is available; please refresh."
131+
// message in the page's interface.
132+
console.log('New or updated content is available.');
133+
} else {
134+
// At this point, everything has been precached.
135+
// It's the perfect time to display a "Content is cached for offline use." message.
136+
console.log('Content is now available offline!');
137+
}
138+
break;
139+
140+
case 'redundant':
141+
console.error('The installing service worker became redundant.');
142+
break;
143+
}
144+
};
145+
};
146+
}).catch(function(e) {
147+
console.error('Error during service worker registration:', e);
148+
});
149+
});
150+
}
151+
}
26152
</script>
27153
</body>
28154
</html>

‎build-system/dist.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ gulp.task('dist:js', 'Compress js to dist.', () => {
4646
gulp.task('dist:html', 'Compress html to dist.', () => {
4747
return gulp.src(['./app/*.html'])
4848
.pipe(cachebust.references())
49-
.pipe($.htmlmin({collapseWhitespace: true}))
49+
.pipe($.htmlmin({collapseWhitespace: true, minifyCSS: true, minifyJS: true}))
5050
.pipe(gulp.dest(distPath))
5151
.pipe($.size({title: 'dist:html'}));
5252
});

‎src/sw.js‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ var isExcluded = function(path) {
4040
}
4141

4242
self.addEventListener('install', function(event) {
43+
self.skipWaiting(); // make new service worker activate ASAP
4344
var now = Date.now();
4445

4546
var urlsToPrefetch = [_FILES_];
@@ -120,6 +121,37 @@ self.addEventListener('activate', function(event) {
120121

121122
self.addEventListener('fetch', function(event) {
122123
console.log('Handling fetch event for', event.request.url);
124+
// https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading
125+
if (event.request.mode === 'navigate') {
126+
// See /web/fundamentals/getting-started/primers/async-functions
127+
// for an async/await primer.
128+
event.respondWith(async function() {
129+
// Optional: Normalize the incoming URL by removing query parameters.
130+
// Instead of https://example.com/page?key=value,
131+
// use https://example.com/page when reading and writing to the cache.
132+
// For static HTML documents, it's unlikely your query parameters will
133+
// affect the HTML returned. But if you do use query parameters that
134+
// uniquely determine your HTML, modify this code to retain them.
135+
const normalizedUrl = new URL(event.request.url);
136+
normalizedUrl.search = '';
137+
138+
// Create promises for both the network response,
139+
// and a copy of the response that can be used in the cache.
140+
const fetchResponseP = fetch(normalizedUrl);
141+
const fetchResponseCloneP = fetchResponseP.then(r => r.clone());
142+
143+
// event.waitUntil() ensures that the service worker is kept alive
144+
// long enough to complete the cache update.
145+
event.waitUntil(async function() {
146+
const cache = await caches.open(CURRENT_CACHES.prefetch);
147+
await cache.put(normalizedUrl, await fetchResponseCloneP);
148+
}());
149+
150+
// Prefer the cached response, falling back to the fetch response.
151+
return (await caches.match(normalizedUrl)) || fetchResponseP;
152+
}());
153+
return;
154+
}
123155
var requestURL = new URL(event.request.url);
124156
if (requestURL.origin == location.origin) {
125157
event.respondWith(

0 commit comments

Comments
 (0)