# Cachê do blog

> Source: <https://gist.github.com/osmar-c/1399efd9f95c8f3a248af70f4d5832d6>
> Published: 2026-05-22 22:13:26+00:00

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

        });

      })

  );

});
