Skip to content

Commit

Permalink
Better asset and offline rule
Browse files Browse the repository at this point in the history
  • Loading branch information
Spomky committed Jan 25, 2024
1 parent 9e3c25c commit e492176
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/Resources/workbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions src/Service/ServiceWorkerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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 = <<<OFFLINE_FALLBACK_STRATEGY
{$offlineFallbackMethod}
{$networkOnlyStrategy}
{$setDefaultHandlerRouting}
offlineFallback({
pageFallback: {$url},
});
Expand Down

0 comments on commit e492176

Please sign in to comment.