From 6705958b6fc8863e8c70cf6fb13b2ae300e7815e Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sat, 9 Mar 2024 09:12:46 +0100 Subject: [PATCH] Features/prefetch on demand (#120) * Prefetch on demand --- assets/package.json | 7 ++++++ assets/src/prefetch-on-demand_controller.js | 24 ++++++++++++++++++ src/Service/Rule/PageCache.php | 16 ++++++++++++ src/Service/Rule/PrefetchOnDemand.php | 27 --------------------- 4 files changed, 47 insertions(+), 27 deletions(-) create mode 100644 assets/src/prefetch-on-demand_controller.js delete mode 100644 src/Service/Rule/PrefetchOnDemand.php diff --git a/assets/package.json b/assets/package.json index 16e0ec2..013a877 100644 --- a/assets/package.json +++ b/assets/package.json @@ -25,6 +25,13 @@ "webpackMode": "eager", "fetch": "eager", "enabled": true + }, + "prefetch-on-demand": { + "main": "src/prefetch-on-demand_controller.js", + "name": "pwa/prefetch-on-demand", + "webpackMode": "eager", + "fetch": "eager", + "enabled": true } }, "importmap": { diff --git a/assets/src/prefetch-on-demand_controller.js b/assets/src/prefetch-on-demand_controller.js new file mode 100644 index 0000000..dec4928 --- /dev/null +++ b/assets/src/prefetch-on-demand_controller.js @@ -0,0 +1,24 @@ +'use strict'; + +import { Controller } from '@hotwired/stimulus'; + +/* stimulusFetch: 'lazy' */ +export default class extends Controller { + static values = { + urls: { type: Array, default: []} + }; + + connect = () => { + const workbox = window.workbox; + if (!workbox) { + return; + } + + workbox.messageSW({ + "type": "PREFETCH", + "payload": { + "urls": this.urlsValue + } + }); + } +} diff --git a/src/Service/Rule/PageCache.php b/src/Service/Rule/PageCache.php index 12a2ccc..54f1abc 100644 --- a/src/Service/Rule/PageCache.php +++ b/src/Service/Rule/PageCache.php @@ -92,6 +92,22 @@ public function process(string $body): string ); event.waitUntil(Promise.all(done)); }); +fetchAsync = async (url) => { + await fetch(url); +} +self.addEventListener('message', (event) => { + if (event.data && event.data.type === 'PREFETCH') { + const urls = event.data.payload.urls || []; + const done = urls.map( + path => + pageCacheStrategy.handleAll({ + event, + request: new Request(path), + })[1] + ); + event.waitUntil(Promise.all(done)); + } +}); PAGE_CACHE_RULE_STRATEGY; return $body . PHP_EOL . PHP_EOL . trim($declaration); diff --git a/src/Service/Rule/PrefetchOnDemand.php b/src/Service/Rule/PrefetchOnDemand.php deleted file mode 100644 index 3c55257..0000000 --- a/src/Service/Rule/PrefetchOnDemand.php +++ /dev/null @@ -1,27 +0,0 @@ - { - await fetch(url); -} -self.addEventListener('message', (event) => { - if (event.data && event.data.type === 'PREFETCH') { - const urls = event.data.payload.urls || []; - urls.forEach((url) => fetchAsync(url)); - } -}); -PREFETCH_STRATEGY; - - return $body . PHP_EOL . PHP_EOL . trim($declaration); - } -}