Skip to content

Commit

Permalink
refactor: add support for sw caching prefetched resources
Browse files Browse the repository at this point in the history
  • Loading branch information
kkemple committed Jul 19, 2018
1 parent 9afeebd commit 95fccb8
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 0 deletions.
45 changes: 45 additions & 0 deletions packages/gatsby-plugin-offline/prefetch-catcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

self.addEventListener("message",
/*#__PURE__*/
function () {
var _ref2 = (0, _asyncToGenerator2.default)(
/*#__PURE__*/
_regenerator.default.mark(function _callee(_ref) {
var data, cache;
return _regenerator.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
data = _ref.data;

if (!(data.type === "prefetch")) {
_context.next = 6;
break;
}

_context.next = 4;
return caches.open("runtimecache");

case 4:
cache = _context.sent;
cache.addAll([data.pathname].concat(data.dependencies));

case 6:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));

return function (_x) {
return _ref2.apply(this, arguments);
};
}());
9 changes: 9 additions & 0 deletions packages/gatsby-plugin-offline/src/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
exports.registerServiceWorker = () => true

exports.onPrefetchPathname = pathData => {
if (`serviceWorker` in navigator) {
navigator.serviceWorker.controller.postMessage({
type: `prefetch`,
...pathData,
})
}
}
1 change: 1 addition & 0 deletions packages/gatsby-plugin-offline/src/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ exports.onPostBuild = (args, pluginOptions) => {
})

const options = {
importScripts: [`./prefetch-catcher.js`],
staticFileGlobs: files.concat([
`${rootDir}/index.html`,
`${rootDir}/manifest.json`,
Expand Down
6 changes: 6 additions & 0 deletions packages/gatsby-plugin-offline/src/prefetch-catcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
self.addEventListener(`message`, async ({ data }) => {
if (data.type === `prefetch`) {
const cache = await caches.open(`runtimecache`)
cache.addAll([data.pathname, ...data.dependencies])
}
})

0 comments on commit 95fccb8

Please sign in to comment.