Home >Web Front-end >JS Tutorial >Service Workers

Service Workers

WBOY
WBOYOriginal
2024-08-09 07:28:421101browse

Service workers are Web APIs that can be used for "specific" purposes between a browser, an application, and the Internet.

Service Workers

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:

1. Offline Support:

  • Service worker caches important resources (HTML, CSS, JavaScript, images) when a user first visits a website.
  • Can retrieve from cache on next visit, providing continuous offline capability.

2. Push Notifications:

  • Service workers allow you to deliver push notifications even when the web application is not open.
  • Notifications can be triggered by external events or server updates.

3. Background Synchronization:

  • Service workers enable background synchronization, which allows an application to update data or fetch new content in the background.
  • This is useful for real-time data updates.

4. Dynamic Content Caching:

  • Service workers can dynamically cache content based on user behavior on a web page.
  • This helps deliver frequently accessed content quickly.

5. Performance Optimization:

  • By pre-caching assets and resources, Service Workers significantly improve web page performance.
  • They can selectively load resources based on user behavior by optimizing the loading process.

6. Background Fetch:

  • Service workers enable background loading, which allows downloading even large files or resources.

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:

Service Workers

If you have a Service worker registered, it will be added as middleware between the web browser and the server:

Service Workers

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.

Service Worker Lifecycle & Event

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.

Service Workers

When we go to the cache storage part, we will get the files we marked with the name we gave.

Service Workers

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn