How to manipulate DOM using a service worker in JavaScript?


In this tutorial, you will learn about JavaScript DOM manipulation using a service worker.

DOM manipulation happens is when we change the structure and elements of the document object model(DOM). We can modify DOM by adding, removing, Changing, or modifying elements and their attributes.

What is a Service worker?

Service workers work like proxy servers between web browsers and the web server. It adds enhancement to the existing websites in case the user’s browser doesn’t support the service worker but he visits any website that uses the service worker then also no function gets affected.

It acts between web applications, browsers, and the network (in case the network is connected). Service worker improves the website reliability by providing offline access in case of no network intercept network request and take the action accordingly and it updates the component residing on the server and boost performance.

Concepts and uses of service worker

Service workers are an enhancement to the existing websites. It is an event-driven worker and works in the form of JavaScript files that can control the website. Service worker-run in worker context is the reason it has no DOM access, and it executes in the background, in a separate thread from the main thread of JavaScript and that’s why it is non-blocking asynchronous.

The service worker uses a cache which makes it possible to function offline in case the network is not there.

Using service workers in JavaScript

The service worker deals with network requests and some asynchronous events. So, it uses promises and asynchronous programming.

Let’s see how to register a service worker.

As all browsers still don’t support service worker so to register a service worker, we should first do a future check. So, we check whether is service worker is present in the navigator or not.

Then to register the service worker, we call the method navigator.serviceWorker.register(), and inside the method, we pass the path to the service worker, this function returns a promise as the service worker is an async event.

if ("serviceWorker" in navigator) {
   navigator.serviceWorker
   .register("service-worker.js")
   .then(function (reg) {
      // Service worker registration successful
   })
   .catch(function (err) {
      // Service worker registration failed.
   });
}

When the promise returns a successful message then we can perform the tasks which is to be performed.

Some standard events of service worker

  • Install

  • Activate

  • Fetch

  • Push

  • Sync

Here push is not supported by safari browser and sync is also not supported by most browsers.

Pre-caching

When the service worker is registered in the install event then the pre-defined assets files is cached before they are requested.

Service-worker.js file code

console.log('Started', self);
self.addEventListener('install', function(event) {
   self.skipWaiting();
   console.log('Installed', event);
});
self.addEventListener('activate', function(event) {
   console.log('Activated', event);
});
self.addEventListener('push', function(event) {
   console.log('Push message received', event);
});

The install event is only called once until the service worker gets updated.

The next event is ‘activate’. So, the service worker doesn’t immediately get active after installation.

The next event is push. MDN says an event is sent to a service worker's global scope (represented by the ServiceWorkerGlobalScope interface) when the service worker has received a push message

Let’s manipulate a DOM element using the program

Here we will change the text color and send the alert message after the successful registration of the service worker.

Create service-worker.js file and add following code −

console.log('Started', self);
self.addEventListener('install', function(event) {
   self.skipWaiting();
   console.log('Installed', event);
});
self.addEventListener('activate', function(event) {
   console.log('Activated', event);
});
self.addEventListener('push', function(event) {
   console.log('Push message received', event);
});

Example

Index.html file

<html>
<head>
   <title>How to get/change the HTML with DOM element in JavaScript?</title>
</head>
<body>
   <h2 id="tut">Change Here</h2>
   <button type="button" onclick="ServiceWorker_Update_dom_Ele()">Get HTML for DOM element</button>
   <script>
      function ServiceWorker_Update_dom_Ele() {
         if ("serviceWorker" in navigator) {
            navigator.serviceWorker
            .register("service-worker.js")
            .then(function (reg) {
               var Element = document.getElementById("tut");
               alert("Service worker registeration successful");
               Element.style.color = "Red";
               Element.innerHTML = "Tutorials Point";
            })
            .catch(function (err) {
               alert("registration failed");
            });
         }
      }
   </script>
</body>
</html>

Remember

Service worker only in secure modes like https or localhost, so running the service worker code in file:// or http would not work. You can open a live server in vs code to make service worker work.

So, so finally you get to know about service worker and the way to manipulate the DOM element.

Updated on: 01-Dec-2022

988 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements