Skip to content

Commit

Permalink
build sw.js
Browse files Browse the repository at this point in the history
  • Loading branch information
unbug committed Dec 26, 2018
1 parent e58dc95 commit c73c4af
Show file tree
Hide file tree
Showing 6 changed files with 488 additions and 5 deletions.
131 changes: 131 additions & 0 deletions app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,136 @@
<body ontouchstart>
<div class="app"></div>
<script src="./js/app.js"></script>
<script>
if (/https/.test(location.protocol) && 'serviceWorker' in navigator) {
if (!Cache.prototype.add) {
Cache.prototype.add = function add(request) {
return this.addAll([request]);
};
}

if (!Cache.prototype.addAll) {
Cache.prototype.addAll = function addAll(requests) {
var cache = this;

// Since DOMExceptions are not constructable:
function NetworkError(message) {
this.name = 'NetworkError';
this.code = 19;
this.message = message;
}
NetworkError.prototype = Object.create(Error.prototype);

return Promise.resolve().then(function() {
if (arguments.length < 1) throw new TypeError();

// Simulate sequence<(Request or USVString)> binding:
var sequence = [];

requests = requests.map(function(request) {
if (request instanceof Request) {
return request;
}
else {
return String(request); // may throw TypeError
}
});

return Promise.all(
requests.map(function(request) {
if (typeof request === 'string') {
request = new Request(request);
}

var scheme = new URL(request.url).protocol;

if (scheme !== 'http:' && scheme !== 'https:') {
throw new NetworkError("Invalid scheme");
}

return fetch(request.clone());
})
);
}).then(function(responses) {
// TODO: check that requests don't overwrite one another
// (don't think this is possible to polyfill due to opaque responses)
return Promise.all(
responses.map(function(response, i) {
return cache.put(requests[i], response);
})
);
}).then(function() {
return undefined;
});
};
}

if (!CacheStorage.prototype.match) {
// This is probably vulnerable to race conditions (removing caches etc)
CacheStorage.prototype.match = function match(request, opts) {
var caches = this;

return this.keys().then(function(cacheNames) {
var match;

return cacheNames.reduce(function(chain, cacheName) {
return chain.then(function() {
return match || caches.open(cacheName).then(function(cache) {
return cache.match(request, opts);
}).then(function(response) {
match = response;
return match;
});
});
}, Promise.resolve());
});
};
}

if ('serviceWorker' in navigator) {
// Delay registration until after the page has loaded, to ensure that our
// precaching requests don't degrade the first visit experience.
// See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration
window.addEventListener('load', function() {
// Your service-worker.js *must* be located at the top-level directory relative to your site.
// It won't be able to control pages unless it's located at the same level or higher than them.
// *Don't* register service worker file in, e.g., a scripts/ sub-directory!
// See https://github.com/slightlyoff/ServiceWorker/issues/468
navigator.serviceWorker.register('sw.js').then(function(reg) {
// updatefound is fired if service-worker.js changes.
reg.onupdatefound = function() {
// The updatefound event implies that reg.installing is set; see
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
var installingWorker = reg.installing;

installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// It's the perfect time to display a "New content is available; please refresh."
// message in the page's interface.
console.log('New or updated content is available.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
console.log('Content is now available offline!');
}
break;

case 'redundant':
console.error('The installing service worker became redundant.');
break;
}
};
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
});
}
}
</script>
</body>
</html>
31 changes: 29 additions & 2 deletions build-system/dist.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
'use strict';

require('date-utils');
const gulp = require('gulp-help')(require('gulp'));
const $ = require('./util');
const pngquant = require('imagemin-pngquant');
const runSequence = require('run-sequence');
const cachebust = $.cachebust();
const through2 = require('through2');


const distPath = './dist';
const buildVersion = (new Date()).toFormat('YYYYMMDDHHMISS');

gulp.task('dist:all', 'Copy all to dist.', () => {
return gulp.src(['./app/**/**'])
Expand Down Expand Up @@ -50,6 +53,30 @@ gulp.task('dist:html', 'Compress html to dist.', () => {
.pipe($.size({title: 'dist:html'}));
});


//generate service workers
gulp.task('dist:serviceworkers', function (cb) {
let resources = ['"./"'];
const rootPath = __dirname.replace('build-system', '') + 'dist/';
gulp.src([distPath + '/**/*.*'])
.pipe(through2.obj(function (file, enc, next) {
!/sw\.js|.*.html/.test(file.path) && this.push('"' + file.path.replace(rootPath,'') + '"');
next();
}))
.on('data', function (data) {
resources.push(data)
})
.on('end', function () {
gulp.src(['./src/sw.js'])
.pipe($.replace(/_BUILD_VERSION_/g, buildVersion))
.pipe($.replace(/_FILES_/g, resources.join(',\n')))
.pipe(gulp.dest(distPath))
.on('end', function () {
cb();
});
});
});

gulp.task('dist', 'Dist the app.', cb => {
runSequence('clean:dist', 'dist:all', 'dist:images', 'dist:css', 'dist:js', 'dist:html', cb);
runSequence('clean:dist', 'dist:all', 'dist:images', 'dist:css', 'dist:js', 'dist:html', 'dist:serviceworkers', cb);
});
2 changes: 1 addition & 1 deletion build-system/lint.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const gulp = require('gulp-help')(require('gulp'));
const $ = require('./util');

gulp.task('lint', 'Lint JS files.', () => {
return gulp.src(['gulpfile.js', 'build-system/**/*.js', 'src/**/*.js*', '!src/vendors/**/**.*'])
return gulp.src(['gulpfile.js', 'build-system/**/*.js', 'src/**/*.js*', '!src/vendors/**/**.*', '!src/sw.js'])
.pipe($.eslint())
.pipe($.eslint.format());
});
130 changes: 129 additions & 1 deletion dist/index.html
Original file line number Diff line number Diff line change
@@ -1 +1,129 @@
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><title>CODELF</title><meta name="description" content="Best GitHub stars, repositories tagger and organizer. Search over projects from Github, Bitbucket, Google Code, Codeplex, Sourceforge, Fedora Project, GitLab to find real-world usage variable names."><meta name="keywords" content="Codelf,变量命名,函数命名,方法命名,变量命名神器,GitHub 分组,Organize GitHub stars,naming things,naming convention,programming naming"><meta http-equiv="x-ua-compatible" content="ie=edge"><link rel="shortcut icon" href="images/codelf_logo.f4ae25bd.png"><link rel="apple-touch-icon" sizes="144x144" href="images/codelf_logo.f4ae25bd.png"><link rel="apple-touch-icon-precomposed" href="images/codelf_logo.f4ae25bd.png"><link title="CODELF" type="application/opensearchdescription+xml" rel="search" href="./opensearch.xml"><link type="text/css" rel="stylesheet" href="./css/lib.365f8ae0.css"><link type="text/css" rel="stylesheet" href="./css/app.79a153d0.css"><script src="js/lib.2ef380a5.js"></script></head><body ontouchstart><div class="app"></div><script src="./js/app.f0f29d58.js"></script></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><title>CODELF</title><meta name="description" content="Best GitHub stars, repositories tagger and organizer. Search over projects from Github, Bitbucket, Google Code, Codeplex, Sourceforge, Fedora Project, GitLab to find real-world usage variable names."><meta name="keywords" content="Codelf,变量命名,函数命名,方法命名,变量命名神器,GitHub 分组,Organize GitHub stars,naming things,naming convention,programming naming"><meta http-equiv="x-ua-compatible" content="ie=edge"><link rel="shortcut icon" href="images/codelf_logo.f4ae25bd.png"><link rel="apple-touch-icon" sizes="144x144" href="images/codelf_logo.f4ae25bd.png"><link rel="apple-touch-icon-precomposed" href="images/codelf_logo.f4ae25bd.png"><link title="CODELF" type="application/opensearchdescription+xml" rel="search" href="./opensearch.xml"><link type="text/css" rel="stylesheet" href="./css/lib.365f8ae0.css"><link type="text/css" rel="stylesheet" href="./css/app.79a153d0.css"><script src="js/lib.2ef380a5.js"></script></head><body ontouchstart><div class="app"></div><script src="./js/app.f0f29d58.js"></script><script>if (/https/.test(location.protocol) && 'serviceWorker' in navigator) {
if (!Cache.prototype.add) {
Cache.prototype.add = function add(request) {
return this.addAll([request]);
};
}

if (!Cache.prototype.addAll) {
Cache.prototype.addAll = function addAll(requests) {
var cache = this;

// Since DOMExceptions are not constructable:
function NetworkError(message) {
this.name = 'NetworkError';
this.code = 19;
this.message = message;
}
NetworkError.prototype = Object.create(Error.prototype);

return Promise.resolve().then(function() {
if (arguments.length < 1) throw new TypeError();

// Simulate sequence<(Request or USVString)> binding:
var sequence = [];

requests = requests.map(function(request) {
if (request instanceof Request) {
return request;
}
else {
return String(request); // may throw TypeError
}
});

return Promise.all(
requests.map(function(request) {
if (typeof request === 'string') {
request = new Request(request);
}

var scheme = new URL(request.url).protocol;

if (scheme !== 'http:' && scheme !== 'https:') {
throw new NetworkError("Invalid scheme");
}

return fetch(request.clone());
})
);
}).then(function(responses) {
// TODO: check that requests don't overwrite one another
// (don't think this is possible to polyfill due to opaque responses)
return Promise.all(
responses.map(function(response, i) {
return cache.put(requests[i], response);
})
);
}).then(function() {
return undefined;
});
};
}

if (!CacheStorage.prototype.match) {
// This is probably vulnerable to race conditions (removing caches etc)
CacheStorage.prototype.match = function match(request, opts) {
var caches = this;

return this.keys().then(function(cacheNames) {
var match;

return cacheNames.reduce(function(chain, cacheName) {
return chain.then(function() {
return match || caches.open(cacheName).then(function(cache) {
return cache.match(request, opts);
}).then(function(response) {
match = response;
return match;
});
});
}, Promise.resolve());
});
};
}

if ('serviceWorker' in navigator) {
// Delay registration until after the page has loaded, to ensure that our
// precaching requests don't degrade the first visit experience.
// See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration
window.addEventListener('load', function() {
// Your service-worker.js *must* be located at the top-level directory relative to your site.
// It won't be able to control pages unless it's located at the same level or higher than them.
// *Don't* register service worker file in, e.g., a scripts/ sub-directory!
// See https://github.com/slightlyoff/ServiceWorker/issues/468
navigator.serviceWorker.register('sw.js').then(function(reg) {
// updatefound is fired if service-worker.js changes.
reg.onupdatefound = function() {
// The updatefound event implies that reg.installing is set; see
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
var installingWorker = reg.installing;

installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// It's the perfect time to display a "New content is available; please refresh."
// message in the page's interface.
console.log('New or updated content is available.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
console.log('Content is now available offline!');
}
break;

case 'redundant':
console.error('The installing service worker became redundant.');
break;
}
};
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
});
}
}</script></body></html>
Loading

0 comments on commit c73c4af

Please sign in to comment.