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. 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 } ; } ; } ;