What Are Web Workers and How to Leverage Them for Optimized Frontend Performance
December 23, 2024

What Are Web Workers and How to Leverage Them for Optimized Frontend Performance

Hello everyone, Vinyl is here again! 👋

Welcome back to my blog. I know it’s been a while, but I’m excited to share some of the latest findings and learnings from a project I worked on this year – a template playground and documentation for drafting, testing, and experimenting with smart legal contracts. Today we’re going to dive into Internet workers: What they are, how they work, and how to use them to enhance your front-end projects.

Well, let’s imagine that you are in a bar having a beer and the bartender (your main thread) has to take the order, prepare the order and clear the counter immediately. If they’re busy making complex orders (which are computationally intensive), then everyone else in line has to wait – that’s frustrating, right? Now imagine that the bartender has an assistant (a web worker) who cleans and organizes pint glasses in the background while the bartender focuses on taking and placing orders. This teamwork ensures smooth operations.

This is just a brief overview. I know you might be thinking APIs from the description, haha, no they are not! Let’s get started.


What is an Internet worker?

Web Workers in web development are like that assistant. They handle heavy lifting in the background, freeing up the main thread to keep your application responsive and smooth. In this article, we’ll take a deep dive into Web Workers, explore their key features, explain how to navigate them, and use three real-life scenarios to demonstrate their power in front-end development. I’ll also provide tips for using Web Workers in other frameworks like Vue, since the main use case here is React.


Three Types of Internet Workers

Before we dive into how to use Web Workers, let’s take a look at the three main types:

Dedicated workers: These are specific to a single script and are the most commonly used workers. They are ideal for tasks such as background calculations or handling API calls for an application instance.

Example: Compress data for a specific user session.

Shared workers: These can be shared between multiple scripts or browser tabs, making them ideal for tasks that require cross-tab communication, such as synchronizing materials across tabs.

Example: Keep user session data consistent across multiple browser tabs.

Service staff: Unlike dedicated and shared worker threads, they intercept network requests and act as a proxy between the application and the network. They are commonly used for caching and offline support.

Example: Provide cached templates when users are offline.

You can read more about these types MDN’s Web Worker documentation.

To know which worker to use, consider the scope of your task:

  • Use Dedicated Workers to perform independent single-script tasks.

  • Use shared workers for multi-tab communication.

  • Use Service Workers to perform network-related tasks such as caching or offline functionality.

The main advantage of Web Workers is the ability to offload these tasks from the main thread, ensuring a smooth user experience. Communication between the main thread and worker threads occurs through the messaging system using the postMessage and onmessage APIs.


Web Worker main features

  • onmessage: Handles messages sent from the main thread to the worker thread.
self.onmessage = (event) => {
  console.log('Message received from main thread:', event.data);
};
Enter full screen mode

Exit full screen mode

  • postMessage: Pass messages from the work thread back to the main thread.
self.postMessage('Task completed');
Enter full screen mode

Exit full screen mode

  • terminate: Stop the work thread from running.
worker.terminate();
Enter full screen mode

Exit full screen mode

  • Error handling:Catch errors in workers.
self.onerror = (error) => {
  console.error('Worker error:', error.message);
};
Enter full screen mode

Exit full screen mode

Other useful features include importScripts Used to load external scripts, self.close for closing staff, and setTimeout/setInterval Used for timing operations. See document Learn more details if needed.


Example use cases in the Web Playground project

Here are three practical scenarios where Web Workers can significantly enhance the example Template Playground project:


Case 1: API call template data

Obtaining template data from the API may result in a large data set that needs to be parsed before use. If you do this directly, this may block the UI thread.

1. Create worker files: create dataParser.worker.js.

// dataParser.worker.js
self.onmessage = (event) => {
  const { rawData } = event.data;
  const parsedData = rawData.map((template) => ({
    name: template.name,
    tag: template.tag,
  }));

  self.postMessage(parsedData);
};
Enter full screen mode

Exit full screen mode

2. Using Workers in React:

import React, { useState } from 'react';

export default function templateDataParser({ rawData }) {
  const [parsedData, setParsedData] = useState([]);

  const parseData = () => {
    const worker = new Worker(new URL('./dataParser.worker.js', import.meta.url));
    worker.postMessage({ rawData });

    worker.onmessage = (event) => {
      setParsedData(event.data);
      worker.terminate();
    };
  };

  return (
    
{JSON.stringify(parsedData, null, 2)}

); }

Enter full screen mode

Exit full screen mode


Case 2: URL compression and decompression

To allow users to share templates via compact URLs, Web Workers efficiently handle compression and decompression.

1. Create worker files: create urlCompressor.worker.js.

// urlCompressor.worker.js
import LZString from 'lz-string';

self.onmessage = (event) => {
  const { action, data } = event.data;
  let result;

  if (action === 'compress') {
    result = LZString.compressToEncodedURIComponent(data);
  } else if (action === 'decompress') {
    result = LZString.decompressFromEncodedURIComponent(data);
  }

  self.postMessage(result);
};

Enter full screen mode

Exit full screen mode

2. Using Workers in React:

import React, { useState } from 'react';

export default function URLCompressor({ template }) {
  const [compressedURL, setCompressedURL] = useState('');

  const compressTemplate = () => {
    const worker = new Worker(new URL('./urlCompressor.worker.js', import.meta.url));
    worker.postMessage({ action: 'compress', data: template });

    worker.onmessage = (event) => {
      setCompressedURL(event.data);
      worker.terminate();
    };
  };

  return (
    
{compressedURL}

); }

Enter full screen mode

Exit full screen mode


Case 3: Processing template loading animation

Web Workers can handle metadata or settings asynchronously when loading multiple templates.

1. Create worker files: create templateLoader.worker.js.

// templateLoader.worker.js
self.onmessage = (event) => {
  const { templates } = event.data;
  const loadedTemplates = templates.map((template) => {
    return { ...template, loadedAt: new Date() };
  });

  self.postMessage(loadedTemplates);
};
Enter full screen mode

Exit full screen mode

2. Using Workers in React:

import React, { useState } from 'react';

export default function TemplateLoader({ templates }) {
  const [loadedTemplates, setLoadedTemplates] = useState([]);

  const loadTemplates = () => {
    const worker = new Worker(new URL('./templateLoader.worker.js', import.meta.url));
    worker.postMessage({ templates });

    worker.onmessage = (event) => {
      setLoadedTemplates(event.data);
      worker.terminate();
    };
  };

  return (
    
{JSON.stringify(loadedTemplates, null, 2)}

); }

Enter full screen mode

Exit full screen mode

Web Workers can improve your work in three scenarios. Feel free to try them out in your own projects and experiments.

Tips for using Web Workers in other frameworks

view: use worker-loader Plugin and call the worker in the Vue element.

angle: Take advantage of Angular’s built-in Web Worker support ng generate web-worker Order.

slim: use vite-plugin-svelte Loader seamlessly imports and uses workers.


in conclusion

Viola, you must be at the end of your rope now! 🎉 Web Workers are like your application’s secret assistants, quietly handling the heavy lifting while your main thread focuses on delivering a great user experience. By using Web Workers in scenarios such as URL compression, API calls, and data preprocessing, you can significantly improve the responsiveness of your application and make the user experience smoother.

So don’t wait, start trying Web Workers today and unleash the full potential of your web applications! See you next time! 👋

refer to

2024-12-23 09:27:16

Leave a Reply

Your email address will not be published. Required fields are marked *