Skip to content

Default to network-first caching strategy #265

@westonruter

Description

@westonruter

The Basic Site Caching plugin contains what have turned out to be the most common baseline caching strategy for sites. In particular, a network-first caching strategy ensures that the freshest content is served when connected to the network with fallbacks for to the cache when the network fails

This is the required code:

<?php
// Enable network-first caching strategy for navigation requests (i.e. clicking around the site).
add_filter(
	'wp_service_worker_navigation_caching_strategy',
	function () {
		return \WP_Service_Worker_Caching_Routes::STRATEGY_NETWORK_FIRST;
	}
);

// Hold on to a certain number of navigated pages in the cache.
add_filter(
	'wp_service_worker_navigation_caching_strategy_args',
	function ( $args ) {
		$args['cacheName'] = 'pages';

		$args['plugins']['expiration']['maxEntries'] = 20;

		return $args;
	}
);

A network-first caching strategy is then also needed for the scripts and styles that a site depends on (coming from core, themes, and plugins). See #264.

A cache-first strategy would also make sense for uploaded files:

<?php
// Add caching for uploaded images.
add_action(
	'wp_front_service_worker',
	function ( \WP_Service_Worker_Scripts $scripts ) {
		$upload_dir = wp_get_upload_dir();
		$scripts->caching_routes()->register(
			'^(' . preg_quote( $upload_dir['baseurl'], '/' ) . ').*\.(png|gif|jpg|jpeg|svg|webp)(\?.*)?$',
			array(
				'strategy'  => \WP_Service_Worker_Caching_Routes::STRATEGY_CACHE_FIRST,
				'cacheName' => 'uploads',
				'plugins'   => array(
					'expiration' => array(
						'maxAgeSeconds' => MONTH_IN_SECONDS,
					),
				),
			)
		);
	}
);

Note that this does not currently account for uploaded files that are hosted on an external CDN, so that should be accounted for as well.

I think this should be the default behavior of the plugin, of course allowing a site to override the default behavior with the filters. Then the PWA plugin would provide for more than just an offline page out of the box. This will in part make #176 obsolete.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions