Home Web Front-end JS Tutorial Service Workers

Service Workers

Aug 09, 2024 am 07:28 AM

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>
Copy after login

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);
      });
  });
}
Copy after login

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))
  );
});
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles