From e492176f5a02d85de064ed3a2088480517dabe9b Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Thu, 25 Jan 2024 23:32:28 +0100 Subject: [PATCH] Better asset and offline rule --- src/Resources/workbox.js | 30 ++++++++++++++++++++++++++-- src/Service/ServiceWorkerBuilder.php | 11 ++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/Resources/workbox.js b/src/Resources/workbox.js index e5c5227..5fb0e5d 100644 --- a/src/Resources/workbox.js +++ b/src/Resources/workbox.js @@ -8,15 +8,41 @@ importScripts( const { pageCache, imageCache, - staticResourceCache, googleFontsCache, } = workbox.recipes; +const {registerRoute} = workbox.routing; +const {CacheFirst} = workbox.strategies; +const {CacheableResponsePlugin} = workbox.cacheableResponse; pageCache();// => Cache pages with a network-first strategy. -staticResourceCache();// => Cache CSS, JS, and Web Worker requests with a cache-first strategy. imageCache();// => Cache images with a cache-first strategy. googleFontsCache();// => Cache the underlying font files with a cache-first strategy. +// *** Assets *** +// Cache CSS, JS, and Web Worker requests with a cache-first strategy. +// We could use staticResourceCache();, but this strategy uses a stale-while-revalidate strategy, +// which is not ideal for static resources served by Asset Mapper (assets are immutable) +const cacheName = 'static-resources'; +const matchCallback = ({request}) => + // CSS + request.destination === 'style' || + // JavaScript + request.destination === 'script' || + // Web Workers + request.destination === 'worker'; + +registerRoute( + matchCallback, + new CacheFirst({ + cacheName, + plugins: [ + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + ], + }) +); + // *** Bundle rules *** //PRECACHING_PLACEHOLDER //WARM_CACHE_URLS_PLACEHOLDER diff --git a/src/Service/ServiceWorkerBuilder.php b/src/Service/ServiceWorkerBuilder.php index 47625c6..a4b01f7 100644 --- a/src/Service/ServiceWorkerBuilder.php +++ b/src/Service/ServiceWorkerBuilder.php @@ -15,6 +15,7 @@ use const JSON_THROW_ON_ERROR; use const JSON_UNESCAPED_SLASHES; use const JSON_UNESCAPED_UNICODE; +use const PHP_EOL; final readonly class ServiceWorkerBuilder { @@ -146,9 +147,19 @@ private function processOfflineFallback(string $body): string $body, 'offlineFallback' ) ? '' : 'const { offlineFallback } = workbox.recipes;'; + $networkOnlyStrategy = str_contains( + $body, + 'NetworkOnly' + ) ? '' : 'const { NetworkOnly } = workbox.strategies;'; + $setDefaultHandlerRouting = str_contains( + $body, + 'setDefaultHandler' + ) ? '' : 'const { setDefaultHandler } = workbox.routing;' . PHP_EOL . 'setDefaultHandler(new NetworkOnly());'; $declaration = <<