{"slug": "cache-do-blog", "title": "Cachê do blog", "summary": "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.", "body_md": "sw.js\n\n      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.\n      \nLearn more about bidirectional Unicode characters\n\n \n    Show hidden characters\n\n// Nome do cache (mude a versão sempre que atualizar o site)\n\nconst CACHE_NAME = 'v1_meu_blog_cache';\n\n// Arquivos que você quer que funcionem offline (adicione os seus aqui)\n\nconst ASSETS_TO_CACHE = [\n\n  '/',\n\n  '/index.html',\n\n  '/css/style.css',  // mude para o caminho real do seu CSS\n\n  '/js/main.js',     // mude para o caminho real do seu JS\n\n  '/favicon.ico'\n\n];\n\n// 1. INSTALAÇÃO: Salva os arquivos essenciais no navegador do usuário\n\nself.addEventListener('install', (event) => {\n\n  event.waitUntil(\n\n    caches.open(CACHE_NAME).then((cache) => {\n\n      console.log('Arquivos guardados no cache com sucesso!');\n\n      return cache.addAll(ASSETS_TO_CACHE);\n\n    })\n\n  );\n\n  // Força o Service Worker atual a se tornar ativo imediatamente\n\n  self.skipWaiting();\n\n});\n\n// 2. ATIVAÇÃO: Remove caches antigos se você atualizar a versão (ex: de v1 para v2)\n\nself.addEventListener('activate', (event) => {\n\n  event.waitUntil(\n\n    caches.keys().then((cacheNames) => {\n\n      return Promise.all(\n\n        cacheNames.map((cache) => {\n\n          if (cache !== CACHE_NAME) {\n\n            console.log('Limpando cache antigo:', cache);\n\n            return caches.delete(cache);\n\n          }\n\n        })\n\n      );\n\n    })\n\n  );\n\n  self.clients.claim();\n\n});\n\n// 3. INTERCEPTAÇÃO (Network First / Network with Cache Fallback):\n\n// Tenta buscar a versão mais recente na internet. Se a internet falhar, usa o cache.\n\nself.addEventListener('fetch', (event) => {\n\n  event.respondWith(\n\n    fetch(event.request)\n\n      .then((response) => {\n\n        // Se a resposta for válida, guarda uma cópia atualizada no cache\n\n        if (response && response.status === 200 && event.request.method === 'GET') {\n\n          const responseToCache = response.clone();\n\n          caches.open(CACHE_NAME).then((cache) => {\n\n            cache.put(event.request, responseToCache);\n\n          });\n\n        }\n\n        return response;\n\n      })\n\n      .catch(() => {\n\n        // Se a internet falhar (offline), busca no cache do navegador\n\n        return caches.match(event.request).then((cachedResponse) => {\n\n          if (cachedResponse) {\n\n            return cachedResponse;\n\n          }\n\n          // Se não estiver no cache e estiver offline, você pode retornar uma página de erro offline aqui\n\n        });\n\n      })\n\n  );\n\n});", "url": "https://wpnews.pro/news/cache-do-blog", "canonical_source": "https://gist.github.com/osmar-c/1399efd9f95c8f3a248af70f4d5832d6", "published_at": "2026-05-22 22:13:26+00:00", "updated_at": "2026-05-23 00:35:15.231041+00:00", "lang": "en", "topics": [], "entities": [], "alternates": {"html": "https://wpnews.pro/news/cache-do-blog", "markdown": "https://wpnews.pro/news/cache-do-blog.md", "text": "https://wpnews.pro/news/cache-do-blog.txt", "jsonld": "https://wpnews.pro/news/cache-do-blog.jsonld"}}