Blog>
Snippets

Conditional Caching Based on Route

A tailored caching example that uses different strategies depending on the specific app route or resource type being requested.
// Function that returns a caching strategy based on the route
function getCacheStrategy(route) {
    // Define custom caching strategies for different routes
    const strategies = {
        '/': 'CacheFirst',
        '/about': 'NetworkFirst',
        '/api/data': 'NetworkOnly'
    };
    // Return the caching strategy for the requested route
    return strategies[route] || 'NetworkFirst';
}
This function determines which caching strategy to use based on the route provided as an argument. It defines a map of routes to caching strategies, and returns the corresponding strategy or a default one if the route is not specified.
// Example of using the getCacheStrategy function in a service worker
self.addEventListener('fetch', event => {
    const route = new URL(event.request.url).pathname;
    const strategy = getCacheStrategy(route);
    // Apply the chosen caching strategy
    // (Pseudocode, replace with actual caching logic)
    switch (strategy) {
        case 'CacheFirst':
            // Serve from cache, fallback to fetch
            break;
        case 'NetworkFirst':
            // Try to fetch from network, fallback to cache
            break;
        case 'NetworkOnly':
            // Always fetch from network, no cache
            break;
        default:
            // Default strategy
            break;
    }
});
This is an example of a service worker event listener for fetch events. It uses the previously defined getCacheStrategy function to determine the caching strategy for the incoming request based on the route. Then, it applies the caching strategy using a switch statement. Actual caching logic should be implemented in place of the pseudocode.