Skip to content

Commit

Permalink
Improve stale-while-revalidate from Google offline-cookbook; add Goog…
Browse files Browse the repository at this point in the history
…le Fonts caching
  • Loading branch information
westonruter committed Jul 10, 2018
1 parent d0ed452 commit c139f50
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 25 deletions.
3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"globals": {
"wp": true,
"window": true,
"document": true
"document": true,
"Set": true
},
"settings": {
"react": {
Expand Down
4 changes: 2 additions & 2 deletions .jshintrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"curly": true,
"eqeqeq": true,
"eqnull": true,
"es3": true,
"esversion": 6,
"expr": true,
"immed": true,
Expand All @@ -22,6 +21,7 @@
"Backbone": false,
"jQuery": false,
"JSON": false,
"wp": false
"wp": false,
"caches": false
}
}
43 changes: 21 additions & 22 deletions assets/js/amp-service-worker-asset-cache.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,35 @@
/* global Promise */
( () => {
/*
* Use a stale-while-revalidate strategy to cache responses from the AMP CDN.
* Use a stale-while-revalidate strategy to cache responses from the AMP CDN and Google Fonts.
* This should eventually be implemented using Workbox.
*/
const CACHE = 'amp';

const cachedOrigins = new Set( [
'https://fonts.googleapis.com',
'https://cdn.ampproject.org',
'https://fonts.gstatic.com'
] );

self.addEventListener( 'fetch', ( event ) => {
if ( 'GET' !== event.request.method ) {
return;
}
const url = new URL( event.request.url );
if ( 'https://cdn.ampproject.org' !== url.origin ) {
if ( ! cachedOrigins.has( url.origin ) ) {
return;
}
event.respondWith( fromCache( event.request ) );
event.waitUntil( update( event.request ) );
} );

function fromCache( request ) {
return caches.open( CACHE ).then( ( cache ) => {
return cache.match( request ).then( ( matching ) => {
return matching || Promise.reject( 'no-match' );
} );
} );
}

function update( request ) {
return caches.open( CACHE ).then( ( cache ) => {
return fetch( request ).then( ( response ) => {
return cache.put( request, response );
} );
} );
}
// Props jakearchibald: https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate
event.respondWith(
caches.open( 'amp' ).then( ( cache ) => {
return cache.match( event.request ).then( ( response ) => {
var fetchPromise = fetch( event.request ).then( ( networkResponse ) => {
cache.put( event.request, networkResponse.clone() );
return networkResponse;
} );
return response || fetchPromise;
} );
} )
);
} );
} )();

0 comments on commit c139f50

Please sign in to comment.