DEV Community

Sh Raj
Sh Raj

Posted on • Updated on • Originally published at codexdindia.blogspot.com

How to make Your Website work offline ๐ŸŒ

Know More :- https://codexdindia.blogspot.com/2024/04/how-to-make-your-website-work-offline.html

Sample Website :- https://sh20raj.github.io/offline-website/ and Source Code :- https://github.com/SH20RAJ/offline-website and Article

So, you wanna make your website work even when the internet decides to take a coffee break? Just like how YouTube lets you download videos for those Wi-Fi-less moments โ›ฑ๏ธ, you can do the same for your website, making it accessible even when the internet's playing hide and seek. Let's dive into creating a site that's like a trusty sidekick, always there for your users, even offline. We'll use the example of HTML5 games ๐Ÿ˜š because, hey, who doesn't love a good game, right? ๐ŸŽฎ

Why You Need Offline Goodness

First things first, let's chat about why having an offline-ready website is a game-changer. Picture this: spotty internet, remote areas, or just a flaky connection โ€“ not everyone's got that smooth, uninterrupted internet flow. By giving your users the option to go offline, you're making sure they can still binge on your content, whether they're in the wilds or on a plane. It's all about leveling up that user experience! ๐Ÿš€

How to Make Your Website an Offline Champ

1. Get Friendly with Service Workers:

Think of Service Workers as the backstage crew for your website's offline performance. They're like your website's bouncer, deciding what to show when the internet's on a break.

  • Register Your Service Worker: Drop this script into your website's HTML to get things rolling:
<script>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js')
      .then(function(registration) {
        console.log('Service Worker registered with scope:', registration.scope);
      }).catch(function(error) {
        console.error('Service Worker registration failed:', error);
      });
  }
</script>
Enter fullscreen mode Exit fullscreen mode
  • Cache the Good Stuff: In your Service Worker file (service-worker.js), stash away the things you want available offline:
var CACHE_NAME = 'my-website-cache-v1';
var urlsToCache = [
  '/',
  '/styles/main.css',
  '/scripts/main.js',
  '/images/logo.png'
];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});
Enter fullscreen mode Exit fullscreen mode
  • Offline Playback: When your user tries to access something offline, the Service Worker jumps in to save the day:
self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        if (response) {
          return response;
        }
        return fetch(event.request);
      })
  );
});
Enter fullscreen mode Exit fullscreen mode

2. Game On with Offline Content:

For HTML5 games or any other content that's gotta work offline, make sure you've got all the pieces ready to go. That means caching HTML, CSS, JavaScript, images โ€“ basically, everything your game needs to run smoothly.

3. Download Feature (Because Why Not?):

Just like how you can download a cat video for later on YouTube, you can let users download your game files directly from your site:

<a href="/path/to/game.zip" download>Download Game</a>
Enter fullscreen mode Exit fullscreen mode

Testing and Sprucing Things Up

  • Testing Time: Before you kick back and relax, give your offline magic a spin. Chrome DevTools' Application panel is your buddy here โ€“ use it to test how your site behaves offline and make any tweaks.

  • Optimization Party: For that extra oomph, think about lazy loading resources and getting smart with your caching. You can even throw in some background sync if your site needs to catch up with the server later on.

Wrapping It Up ๐ŸŽ

Making your website a chill hangout spot, even without the internet, is a win-win. Users can dive into your content wherever they are, no internet needed. By bringing in Service Workers, caching the essentials, and maybe even tossing in a download feature, you're setting the stage for an awesome offline experience. So go ahead, give your users that offline high-five, and watch your site become their go-to even when the internet's taking a nap. ๐ŸŒŸ


Download This Article :- https://gist.github.com/SH20RAJ/5005647373b6c5dd94fec8a5a673cb7d

Top comments (16)

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.