DEV Community

How to make Your Website work offline 🌐

Sh Raj on April 05, 2024

Know More :- https://codexdindia.blogspot.com/2024/04/how-to-make-your-website-work-offline.html Sample Website :- https://sh20raj.github.io/offl...
Collapse
 
sebastianccc profile image
Sebastian Christopher

Awesome post. We really need to spread the word about this stuff. Might I suggest adding to the post - "what you’re actually building" - a PWA. (Progressive Web App)πŸ™‚. Another thing to consider, offline only works if the user initially had WiFi while visiting your website, for it to download the service worker. πŸ˜‰

Collapse
 
sh20raj profile image
Sh Raj

Obviously 😊

Collapse
 
anitaolsen profile image
Anita Olsen*Β°β€’.β˜†

Thank you so much for sharing this! This is AWESOME stuff! ✨

If I may? I believe your title would be in better English if you wrote "work" instead of "used"? and the sentence would sound much better if you wrote the following instead: "How to Make Your Website Work Without Internet" or "How to Make Your Website Work Offline" πŸ™‚

Keep up the good work! ✨

Collapse
 
sh20raj profile image
Sh Raj

Thanks for the Work 😊

Collapse
 
anitaolsen profile image
Anita Olsen*Β°β€’.β˜†

You are very welcome! πŸ˜€

Collapse
 
sh20raj profile image
Sh Raj

Updated the title to yours and
Glad to know that it helped you β™₯️

Collapse
 
best_codes profile image
Best Codes
Collapse
 
razielrodrigues profile image
Raziel Rodrigues

Perfect

Collapse
 
sh20raj profile image
Sh Raj

Thanks for the appreciation πŸ˜‡

Collapse
 
kingtony01 profile image
King Tony

Damn buddy 😊
I so much love this article.

Collapse
 
sh20raj profile image
Sh Raj

Thanks for the compliment brother πŸ˜‡

Collapse
 
nicholasbalette profile image
Nicholasbalette

So many to learn , there is always a way to go.

Collapse
 
mayankt18 profile image
Mayank Thakur

Awesome content

Collapse
 
testybryan profile image
Testy Bryan

Wow, I've learned a lot... Thanks so much

Collapse
 
livetvchannels profile image
Trieu.iv • Edited

// app.js

if ("serviceWorker" in navigator && window.location.protocol === "https:") {
        navigator.serviceWorker
            .register("/ServiceWorker.js")
            .then((registration) => {
                if (registration.waiting) {
                    registration.waiting.postMessage("skipWaiting");
                }
            })
            .catch((error) => {
                console.error('Service Worker registration failed:', error);
            });
    }
Enter fullscreen mode Exit fullscreen mode

// ServiceWorker.js

// I use workbox for more options
import { clientsClaim, cacheNames } from 'workbox-core';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate, NetworkFirst } from 'workbox-strategies';
import { precacheAndRoute, getCacheKeyForURL } from 'workbox-precaching';
import { ExpirationPlugin } from 'workbox-expiration';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
// import * as googleAnalytics from 'workbox-google-analytics';
// import * as navigationPreload from 'workbox-navigation-preload';

clientsClaim();
self.skipWaiting();

self.addEventListener('activate', event => {
    event.waitUntil(async function () {
        const userCacheNames = await caches.keys();
        await Promise.all(userCacheNames.map(async cacheName => {
            if (!Object.values(cacheNames).includes(cacheName)) {
                return await caches.delete(cacheName);
            }
            return await Promise.resolve();
        }));
        // Enable navigation preload.
        // https://developer.chrome.com/docs/workbox/modules/workbox-navigation-preload/
        // https://web.dev/navigation-preload/
        // Feature-detect
        if (self.registration.navigationPreload) {
            // Enable navigation preloads!
            await self.registration.navigationPreload.enable();
        }
    }());
});

// if (typeof Workbox !== 'undefined') {
const revision = Date.now().toString();

precacheAndRoute([
    { url: '/favicon.ico', revision: revision },
    { url: '/favicon.svg', revision: revision }
]);

registerRoute(
    ({ url }) =>
url.origin === 'https://live-tv-channels.org' &&
        url.pathname.startsWith('/assets/') &&
        url.pathname.match(/\.(png|jpg|jpeg|svg|gif|webp|css|js|ico|woff2|ttf)$/),
    new StaleWhileRevalidate({
        cacheName: 'assets',
        plugins: [
            new CacheableResponsePlugin({
                statuses: [0, 200],
            }),
            new ExpirationPlugin({
                maxAgeSeconds: 7 * 24 * 60 * 60, // Cache for 7 days
            }),
        ],
        // fallbackTo: 'network', // Fallback to network if no update found
    })
);```

Enter fullscreen mode Exit fullscreen mode
Collapse
 
jilljj profile image
Jill Johnson

A very good idea indeed! I was going through some Windows 2000 cd's and found the html for those animated sites, flash, and pdf cookbooks made into exe's without too much coding, although flash was a beast to get through...and the cd's are still in good condition. I wonder if they have any value beyond becoming melted-down faux mosaic tiles and jewelry, but that is another question altogether. Auto-play cd's made a nice little portfolio business card on the road and at events. I miss w2k and cds.