I created a PWA via Vue CLI which is consuming an external API. The API responses should get cached for offline access.
From the docs https://cli.vuejs.org/core-plugins/pwa.html#configuration I created a vue.config.js file in the root directory
module.exports = {
publicPath: '/pwa',
pwa: {
appleMobileWebAppCapable: 'yes',
workboxPluginMode: 'GenerateSW',
workboxOptions: {
runtimeCaching: [
{
urlPattern: new RegExp('^https://example.com/'),
handler: 'networkFirst', // Network first, Cache fallback
options: {
networkTimeoutSeconds: 5,
cacheName: 'api-cache',
cacheableResponse: {
statuses: [0, 200],
},
},
},
],
},
},
};
The project is working fine but I want to avoid loading data from the API on a very bad connection.
I want to load data on WLAN network connection only. Is there a way I can extend the configuration and set a network type to detect? The configuration should be called
use network first but only with WLAN, otherwise use cache as fallback
You'll need to switch from using Workbox's GenerateSW
to using the InjectManifest
mode, which gives you more control over the service worker.
The example in https://developers.google.com/web/tools/workbox/guides/get-started can get you started with the basics of what to include in your service worker file.
Just note that the Network Information API isn't always reliable, and isn't supported in all browsers. You should code defensively so that the experience isn't "broken" if the API isn't available.
The specific logic that you can add to your service worker could go something like:
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {NetworkFirst, CacheFirst} from 'workbox-strategies';
import {registerRoute} from 'workbox-routing';
// This will be shared by both the strategies.
const cacheableResponsePlugin = new CacheableResponsePlugin({
statuses: [0, 200],
});
const networkFirst = new NetworkFirst({
cacheName: 'api-cache',
networkTimeoutSeconds: 5,
plugins: [cacheableResponsePlugin],
});
const networkFirst = new CacheFirst({
cacheName: 'api-cache',
plugins: [cacheableResponsePlugin],
});
registerRoute(
// Replace with the routing criteria appropriate for your API.
({url}) => url.origin === 'https://example.com',
(params) => {
// navigator.connection might not always be available, and might not
// always be reliable.
// See https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
if (navigator.connection?.effectiveType === '4g') {
return networkFirst.handle(params);
}
// If the current connection is not flagged as '4g',
// or if navigator.connection isn't set, use CacheFirst
// as a fallback.
return cacheFirst.handle(params);
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.