cd /news/general/cache-do-blog · home topics general article
[ARTICLE · art-10368] src=gist.github.com ↗ pub= topic=general verified=true sentiment=· neutral

Cachê do blog

The article provides a JavaScript code snippet for a blog's Service Worker, which is used to enable offline functionality by caching essential files like HTML, CSS, and JavaScript. It explains the three main lifecycle events: installation (saving files to cache), activation (clearing old caches), and fetch interception (serving cached content when the network is unavailable). The code implements a "network first" strategy, attempting to fetch the latest version from the internet and falling back to the cache if the request fails.

read2 min views19 publishedMay 22, 2026

sw.js

  This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

Learn more about bidirectional Unicode characters

Show hidden characters
// Nome do cache (mude a versão sempre que atualizar o site)

const CACHE_NAME = 'v1_meu_blog_cache';

// Arquivos que você quer que funcionem offline (adicione os seus aqui)

const ASSETS_TO_CACHE = [

'/',

'/index.html',

'/css/style.css', // mude para o caminho real do seu CSS

'/js/main.js', // mude para o caminho real do seu JS

'/favicon.ico'

];

// 1. INSTALAÇÃO: Salva os arquivos essenciais no navegador do usuário

self.addEventListener('install', (event) => {

event.waitUntil(

    caches.open(CACHE_NAME).then((cache) => {

      console.log('Arquivos guardados no cache com sucesso!');

      return cache.addAll(ASSETS_TO_CACHE);

    })

  );

  // Força o Service Worker atual a se tornar ativo imediatamente

  self.skipWaiting();

});

// 2. ATIVAÇÃO: Remove caches antigos se você atualizar a versão (ex: de v1 para v2)

self.addEventListener('activate', (event) => {

event.waitUntil(

    caches.keys().then((cacheNames) => {

      return Promise.all(

        cacheNames.map((cache) => {

          if (cache !== CACHE_NAME) {

            console.log('Limpando cache antigo:', cache);

            return caches.delete(cache);

          }

        })

      );

    })

  );

  self.clients.claim();

});

// 3. INTERCEPTAÇÃO (Network First / Network with Cache Fallback):

// Tenta buscar a versão mais recente na internet. Se a internet falhar, usa o cache.

self.addEventListener('fetch', (event) => {

event.respondWith(

    fetch(event.request)

      .then((response) => {

        // Se a resposta for válida, guarda uma cópia atualizada no cache

        if (response && response.status === 200 && event.request.method === 'GET') {

          const responseToCache = response.clone();

          caches.open(CACHE_NAME).then((cache) => {

            cache.put(event.request, responseToCache);

          });

        }

        return response;

      })

      .catch(() => {

        // Se a internet falhar (offline), busca no cache do navegador

        return caches.match(event.request).then((cachedResponse) => {

          if (cachedResponse) {

            return cachedResponse;

          }

          // Se não estiver no cache e estiver offline, você pode retornar uma página de erro offline aqui

        });

      })

  );

});
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
Live at https://your-agent.zahid.host
Get free account → Pricing
from €0/mo · no card required
LIVE [news/cache-do-blog] indexed:0 read:2min 2026-05-22 ·