Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // JavaScript Document
- // Important! Paths are relative to root. Soft link to this file from root to
- // avoid scope restrictions.
- 'use strict;
- // Listen for request events
- self.addEventListener('fetch', function (event) {
- // Get the request
- let request = event.request;
- // Bug fix
- // https://stackoverflow.com/a/49719964
- if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') return;
- // HTML files
- // Network-first
- if (request.headers.get('Accept').includes('text/html')) {
- event.respondWith(
- fetch(request).then(function (response) {
- // Create a copy of the response and save it to the cache
- let copy = response.clone();
- event.waitUntil(caches.open('app').then(function (cache) {
- // This is the line that throws an error:
- return cache.put(request, copy);
- }));
- // Return the response
- return response;
- }).catch(function (error) {
- return caches.match(request).then(function (response) {
- return response;
- });
- })
- );
- }
- // CSS, JavaScript, images, & fonts
- // Offline-first
- if (request.headers.get('Accept').includes('text/css') || request.headers.get('Accept').includes('text/javascript') || request.headers.get('Accept').includes('image') || request.headers.get('Accept').includes('font')) {
- // Check the cache first
- // If it's not found, send the request to the network
- event.respondWith(
- caches.match(request).then(function (response) {
- return response || fetch(request).then(function (response) {
- return response;
- });
- })
- );
- return;
- }
- });
- let coreAssets = [
- // Paths to core assets.
- ];
- // On install, cache some stuff
- self.addEventListener('install', function (event) {
- // Cache core assets
- event.waitUntil(caches.open('app').then(function (cache) {
- for (let asset of coreAssets) {
- cache.add(new Request(asset));
- }
- return cache;
- }));
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement