Skip to content

Instantly share code, notes, and snippets.

@zolotyh
Created February 27, 2025 12:59
Show Gist options
  • Save zolotyh/88c3c5fefabe31b58b0bdc65440d8ff1 to your computer and use it in GitHub Desktop.
Save zolotyh/88c3c5fefabe31b58b0bdc65440d8ff1 to your computer and use it in GitHub Desktop.
ServiceWorker example

Here’s a full example in React that demonstrates how to check if a file is cached by a Service Worker (using Workbox) and display the cache status to the user.


1. Set Up Workbox in Webpack

Ensure you have Workbox set up in your webpack.config.js:

const WorkboxWebpackPlugin = require('workbox-webpack-plugin');

module.exports = {
  plugins: [
    new WorkboxWebpackPlugin.GenerateSW({
      clientsClaim: true,
      skipWaiting: true,
      runtimeCaching: [
        {
          urlPattern: /\.(?:png|jpg|jpeg|svg|css|js)$/,
          handler: 'CacheFirst',
        },
      ],
    }),
  ],
};

This configuration will cache static assets like images, CSS, and JS files.


2. Register the Service Worker

In your index.js or serviceWorkerRegistration.js, register the Service Worker:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker
      .register('/service-worker.js')
      .then((registration) => {
        console.log('Service Worker registered: ', registration);
      })
      .catch((error) => {
        console.log('Service Worker registration failed: ', error);
      });
  });
}

3. Create the React Component

Create a React component that checks if a specific file is cached and displays the status to the user.

import React, { useState, useEffect } from 'react';

const CacheStatusChecker = () => {
  const [isCached, setIsCached] = useState(null);
  const fileUrl = '/path/to/your/file.js'; // Replace with the file you want to check

  useEffect(() => {
    const checkCacheStatus = async () => {
      try {
        // Open the cache used by Workbox
        const cache = await caches.open('workbox-precache'); // Replace with your cache name if different
        const response = await cache.match(fileUrl);
        setIsCached(!!response); // Set true if cached, false otherwise
      } catch (error) {
        console.error('Error checking cache:', error);
        setIsCached(false);
      }
    };

    checkCacheStatus();
  }, [fileUrl]);

  return (
    <div>
      <h2>Cache Status</h2>
      {isCached === null ? (
        <p>Checking cache status...</p>
      ) : isCached ? (
        <p style={{ color: 'green' }}>The file is cached! 🎉</p>
      ) : (
        <p style={{ color: 'red' }}>The file is not cached. 😢</p>
      )}
    </div>
  );
};

export default CacheStatusChecker;

4. Use the Component in Your App

Include the CacheStatusChecker component in your App.js or any other component:

import React from 'react';
import CacheStatusChecker from './CacheStatusChecker';

function App() {
  return (
    <div>
      <h1>Workbox Cache Checker</h1>
      <CacheStatusChecker />
    </div>
  );
}

export default App;

5. Run the Application

  • Build your application using npm run build or yarn build.
  • Serve the build folder using a static server (e.g., serve -s build).
  • Open the application in your browser.

The CacheStatusChecker component will:

  1. Check if the specified file is cached.
  2. Display a message indicating whether the file is cached or not.

6. Testing

  • Ensure the file you're checking (e.g., /path/to/your/file.js) is included in the Workbox precache or runtime cache configuration.
  • Reload the page to see the cache status update.

7. Optional: Add a Button to Recheck Cache Status

If you want to allow users to manually recheck the cache status, you can add a button:

import React, { useState, useEffect } from 'react';

const CacheStatusChecker = () => {
  const [isCached, setIsCached] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const fileUrl = '/path/to/your/file.js'; // Replace with the file you want to check

  const checkCacheStatus = async () => {
    setIsLoading(true);
    try {
      const cache = await caches.open('workbox-precache');
      const response = await cache.match(fileUrl);
      setIsCached(!!response);
    } catch (error) {
      console.error('Error checking cache:', error);
      setIsCached(false);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    checkCacheStatus();
  }, [fileUrl]);

  return (
    <div>
      <h2>Cache Status</h2>
      {isLoading ? (
        <p>Checking cache status...</p>
      ) : isCached === null ? (
        <p>Cache status unknown.</p>
      ) : isCached ? (
        <p style={{ color: 'green' }}>The file is cached! 🎉</p>
      ) : (
        <p style={{ color: 'red' }}>The file is not cached. 😢</p>
      )}
      <button onClick={checkCacheStatus} disabled={isLoading}>
        Recheck Cache Status
      </button>
    </div>
  );
};

export default CacheStatusChecker;

Summary

This example demonstrates how to:

  • Check if a file is cached by the Service Worker at runtime.
  • Display the cache status in a React component.
  • Allow users to manually recheck the cache status.

You can adapt this example to check multiple files or display more detailed cache information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment