Created
March 1, 2023 00:20
-
-
Save westonruter/3beda9d304c02712cbb0f01ba06aa5b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* PWA Cache Pre-Activation Resources | |
* | |
* @package PWA | |
* @author Weston Ruter | |
* @link https://gist.github.com/westonruter/3beda9d304c02712cbb0f01ba06aa5b2 | |
* @license GPL-2.0-or-later | |
* @copyright 2019 Google Inc. | |
* | |
* @wordpress-plugin | |
* Plugin Name: PWA Cache Initial Assets Upon Activation | |
* Plugin URI: https://gist.github.com/westonruter/3beda9d304c02712cbb0f01ba06aa5b2 | |
* Description: Add page resources loaded before the service worker was initially activated to the runtime cache. | |
* Version: 0.1.0 | |
* Author: Weston Ruter | |
* Author URI: https://weston.ruter.net/ | |
* License: GNU General Public License v2 (or later) | |
* License URI: http://www.gnu.org/licenses/gpl-2.0.html | |
*/ | |
// See https://developer.chrome.com/docs/workbox/modules/workbox-window/#send-the-service-worker-a-list-of-urls-to-cache | |
// See https://github.com/GoogleChrome/workbox/blob/95f97a207fd51efb3f8a653f6e3e58224183a778/packages/workbox-routing/src/Router.ts#L88-L109 | |
add_action( | |
'wp_print_footer_scripts', | |
static function () { | |
?> | |
<script type="module"> | |
if (window.wp && wp.serviceWorkerWindow) { | |
wp.serviceWorkerWindow.addEventListener('activated', () => { | |
// Get all resources the page loaded. Note that this cannot | |
// include the current page URL because it is handled by | |
// NavigationRoute and not by the default router per the | |
// note at: https://developer.chrome.com/docs/workbox/modules/workbox-window/#send-the-service-worker-a-list-of-urls-to-cache:~:text=The%20above%20technique%20works%20for%20any%20route%20defined%20via | |
const urlsToCache = [ | |
...performance.getEntriesByType('resource').map(r => r.name), | |
]; | |
// Send that list of URLs to your router in the service worker. | |
wp.serviceWorkerWindow.messageSW({ | |
type: 'CACHE_URLS', | |
payload: { | |
urlsToCache | |
}, | |
}); | |
}); | |
} | |
</script> | |
<?php | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment