Service workers are scripts that run in the background of a web application, separate from the main browser thread. They enable push notifications, background synchronization, and offline capabilities. Service workers work as an intermediary between the web application, the browser and the network. Here are examples of how and when service workers can be used:
Usually, when you visit a web page, the web page sends a request to the server, and the server sends the data back to you:
If you have a Service worker registered, it will be added as middleware between the web browser and the server:
It stops the request to the server and decides whether the request is sent to the server or works offline. And instead of showing you a 404 Not Found page in this case, you will be able to view the entire page offline. You can also create custom offline pages with service workers.
Usually, if there is no internet on your computer, it will show you an error page.
Even if there is no Internet, we will access the web page with a service worker.
REGISTER → INSTALL → ACTIVATE → FETCH
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Home</title> <!-- Scripts --> <script src="main.js" defer></script> </head> <body> <!-- istalgan kodlaringizni yozishingiz mumkin... --> </body> </html>
we connected the main.js file to html.
main.js
// service worker browser tomonidan support qilinishini tekshirib olamiz if ('serviceWorker' in navigator) { // web sahifa browserga yuklanishi bilan ishlashini aytib o'tamiz window.addEventListener('load', () => { // 1. service workerni registratsiyadan o'tkazamiz. navigator.serviceWorker .register('sw.js') // bizda sm.js file ochib olishimiz kerak bo'ladi. va bu yerdagi register ushani target qiladi. .then((registration) => console.log('Service Worker registered with scope:', registration.scope) ) .catch((error) => { console.error('Service Worker registration failed:', error); }); }); }
sw.js
// browser kashda qanday nom nilan saqlanishini bildirish uchun nom beramiz const cacheName = 'my-cache-v1'; // Qaysi fayllarni kashlashini aytib o'tib ketamiz const cacheFiles = ['index.html', 'posts.html', 'css/style.css', 'js/main.js']; // 2. INSTALL qilamiz self.addEventListener('install', (event) => { event.waitUntil( // kashdan biz bergan nom bilan joy ochadi va bizni fayllarimizni joylaydi. caches.open(cacheName).then((cache) => cache.addAll(cacheFiles)) ); }); // 3. ACTIVATE qilish self.addEventListener('activate', () => { console.log('Server worker activated'); }); // 4. FETCH, ya'ni oflayn holatimizda kashlangan fillarni ko'rsatish uchun olish self.addEventListener('fetch', (event) => { event.respondWith( caches .match(event.request) .then((response) => response || fetch(event.request)) ); });
After doing this, we can see that activation has occurred if we go to the Applications column in the browser's dev tools section and see the Service workers section.
When we go to the cache storage part, we will get the files we marked with the name we gave.
And after looking at these, we can see the result:
As you can see, it works offline now. In the offline state, the Service Worker is fetching it from the place it opened for us in Cache Storage.
@abdulakhatov-dev
@AbdulakhatovDev
The above is the detailed content of Service Workers. For more information, please follow other related articles on the PHP Chinese website!