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.
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.
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);
});
});
}
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;
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;
- Build your application using
npm run build
oryarn build
. - Serve the build folder using a static server (e.g.,
serve -s build
). - Open the application in your browser.
The CacheStatusChecker
component will:
- Check if the specified file is cached.
- Display a message indicating whether the file is cached or not.
- 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.
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;
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.