Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add offline support via a service worker
The service worker intercepts fetch requests so that when offline, the cached
version of site resources will be returned. This enables offline support in
manual testing with Chrome on Android and Firefox on Android, and Lighthouse
gives it a 92% overall score and confirms that it works offline.

Uses the boilerplate service worker registration code from
https://github.com/GoogleChrome/sw-precache/blob/master/demo/app/js/service-worker-registration.js
to load a service worker built on the sw-precache library, which handles
precaching of our smaller local static files, and dynamic runtime caching for
external resources and our large audio file.

The service worker generation gulp task runs after the styles and scripts
tasks.  If the scripts and styles don't exist when sw-precache runs, then they
won't get added to the precache list. Which makes it pretty hard to have this
operate offline.

Signed-off-by: Dan Scott <dan@coffeecode.net>
  • Loading branch information
dbs committed Feb 8, 2017
commit 731cf3899eb162fb7953cf2fff5a5248a328ca1e
37 changes: 34 additions & 3 deletions gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
autoprefixer = require('gulp-autoprefixer'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename');
rename = require('gulp-rename'),
swPrecache = require('sw-precache'),
packageJson = require('./package.json');

const config = {
js : {
Expand All @@ -20,6 +22,35 @@ const config = {
}
}

function writeServiceWorkerFile(callback) {
swConfig = {
cacheId: packageJson.name,
runtimeCaching: [{
urlPattern: /^https:\/\/cdn\.rawgit\.com\//,
handler: 'cacheFirst'
},{
urlPattern: /^https:\/\/aframe\.io\//,
handler: 'cacheFirst'
},{
urlPattern: /\/assets\/sounds\//,
handler: 'cacheFirst'
}],
staticFileGlobs: [
'assets/fonts/fabrica-webfont.woff',
'assets/images/bg.jpg',
'assets/images/tree_icon.png',
'assets/models/**.dae',
'bundle.css',
'bundle.js',
'index.html'
]
}
swPrecache.write('service-worker.js', swConfig, callback);
}

gulp.task('generate-service-worker', ['scripts', 'styles'], function(callback) {
writeServiceWorkerFile(callback);
});

gulp.task('scripts', () =>{
return gulp.src(config.js.in)
Expand Down Expand Up @@ -60,5 +91,5 @@ gulp.task('watch', () =>{
})
})

gulp.task('deploy',['scripts','styles'])
gulp.task('default',['deploy','watch'])
gulp.task('deploy',['scripts','styles','generate-service-worker'])
gulp.task('default',['deploy','watch'])
65 changes: 65 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,71 @@
<link rel="stylesheet" href="bundle.css">
<script src="https://aframe.io/releases/0.3.2/aframe.min.js"></script>
<script src="https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/aframe-particle-system-component.min.js"></script>
<script>
/**
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Source: https://github.com/GoogleChrome/sw-precache/blob/master/demo/app/js/service-worker-registration.js

/* eslint-env browser */
'use strict';

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('service-worker.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>

</head>
<body>
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"gulp-autoprefixer": "^3.1.1",
"gulp-rename": "^1.2.2",
"gulp-ruby-sass": "^2.1.1",
"gulp-uglify": "^2.0.0"
"gulp-uglify": "^2.0.0",
"sw-precache": "^4.3.0"
},
"keywords": [
"aframe",
Expand Down