How to use Web Workers to improve performance?

I. Overview

Web Workers enable a web application to run a script operation in a background thread separate from the main execution thread. The advantage of this is that time-consuming processing tasks can be performed in a separate thread, allowing the main (usually UI) thread to run without being blocked.

Its function is to create a multi-threaded running environment for JS, allowing the main thread to create a worker thread and assign tasks to the latter. While the main thread is running, the worker thread is also running without interfering with each other. After the worker thread finishes running, the result is returned to main thread. The advantage of this is that the main thread can hand over computationally intensive or high-latency tasks to the worker thread for execution, so that the main thread will become relaxed and will not be blocked or slowed down. This does not mean that the JS language itself supports multi-threading capabilities, but that the browser as the host environment provides a multi-threaded running environment for JS.

However, once a worker is created, it will run all the time and will not be interrupted by the activities of the main thread. This is conducive to responding to the connectivity of the main thread at any time, but it will also cause a waste of resources, so it should not be used excessively, and be careful to close it when it is used up. . In other words: if the worker has no instance reference, the worker will be closed immediately after being idle; if the worker real column reference is not 0, the worker will not be closed when it is idle.

2. Usage scenarios

In the front-end process, if we encounter some time-consuming application scenarios, we can use web workers to create new threads to improve the running fluency of the main thread and improve performance. Possible scenarios are as follows:

  • encrypted data

    Some encryption and decryption algorithms are more complicated, or when encrypting and decrypting a lot of data, it will consume a lot of computing resources and cause the UI thread to become unresponsive. Therefore, this is a good time to use Web Worker. Using Worker threads can make users more seamless Operate the UI.

  • prefetch data

    Sometimes in order to improve the data loading speed, you can use Worker threads to obtain data in advance, because Worker threads can be XMLHttpRequestused .

  • pre-rendered

    In some rendering scenarios, such as rendering complex canvas, effects such as reflection, refraction, light and shadow, materials, etc. need to be calculated. The logic of these calculations can be executed using Worker threads, or multiple Worker threads can be used. Here is a Example of ray tracing .

  • complex data processing

    Certain retrieval, sorting, filtering, and analysis are very time-consuming. At this time, Web Worker can be used to do it without occupying the main thread.

  • preload images

    Sometimes a page has many pictures, or a few large pictures, if business constraints do not consider lazy loading, you can also use Web Worker to load pictures, you can refer to the exploration of this article , here is a brief summary.

3. Grammar

Worker()The constructor creates a Workerobject that executes the specified URL script. This script must obey the same-origin policy .

const myWorker = new Worker(aURL, options);

1. Parameters

  • Raises a SecurityError if the document does not allow starting a worker

  • A NetworkError is raised if one of the scripts has a MIME type of text/csv, image/*, video/*, or audio/*. It should always be text/javascript.

  • Raises SyntaxError if aURL cannot be resolved.

  • URL

    • : is a URL DOMStringrepresenting the script that the worker will execute. It must obey the same-origin policy.
  • options

    optional

    • : An object containing options properties that can be set when creating an object instance. The available properties are as follows:
      • type: Used to specify DOMStringthe value . The value can be classicor module. If not specified, a default value will be usedclassic.
      • credentials: Used to specify DOMStringthe value . The value can be * omit*, same-origin, or include. If not specified, or type is classic, the default will be used omit(no credentials requested).
      • * name: * In the case DedicatedWorkerGlobalScopeof , it is used to represent a DOMStringvalue of the scope of the worker, which is mainly used for debugging purposes.

2. Return value

Created workers.

5. Use

1. Permanent memory

index.vue code :

<template>
    web worker
    <el-button @click="save" type="primary">保存</el-button>
</template>
<script setup lang="ts">
import { onMounted } from "vue";

const saveWorker = new Worker(
    new URL("./worker.ts", import.meta.url),
    {
        type: "module",
    }
);
saveWorker.onmessage = (e: any) => {
    if (e.data.error) {
        console.error("自动保存失败,请联系管理员!");
    } else {
        console.log("自动保存成功!");
    }
};
const save = () => {
    saveWorker.postMessage({
        frameData: { a: 1, b: 2 },
        editorToken: "123456",
    });

}
onMounted(() => {
})
</script>

<style lang="scss"></style>

worker.ts code:

import axios from "axios";

self.addEventListener("message", async (e) => {
    
    
    const frameData = e.data.frameData;
    const token = e.data.editorToken;
    let params = {
    
     frameData, token };
    let res = await axios({
    
    
        url: "/api/get",
        method: "get",
        params: params,
    })
    if (res.data.code !== 0) {
    
    
        // worker线程发送消息
        (self as any).postMessage({
    
    
            error: true,
        });
        return;
    }
    // worker线程发送消息
    (self as any).postMessage({
    
    
        error: false,
        data: res.data.data
    });
});

export {
    
     };

2. Temporary use

index.vue code :

//index.vue
<template>
    web worker
    <el-button @click="save" type="primary">保存</el-button>
</template>
<script setup lang="ts">
import { onMounted } from "vue";

const save = () => {
    //每次使用都单独创建
    const saveWorker = new Worker(
        new URL("./worker.ts", import.meta.url),
        {
            type: "module",
        }
    );
    saveWorker.onmessage = (e: any) => {
        if (e.data.error) {
            console.error("自动保存失败,请联系管理员!");
        } else {
            console.log("自动保存成功!");
        }
    };
    saveWorker.postMessage({
        frameData: { a: 1, b: 2 },
        editorToken: "123456",
    });

}
onMounted(() => {
})
</script>

<style lang="scss"></style>

worker.ts code:

//worker.ts
import axios from "axios";

self.addEventListener("message", async (e) => {
    
    
    //...同上

    (self as any).close();//用完就关闭
});

export {
    
     };

6. Restrictions on Use

There are some points to note about the use of worker threads

  1. The same origin restricts
    the script file executed by the worker thread to be of the same origin as the script file of the main thread. Of course, the worker thread cannot be allowed to read files everywhere on other people's computers.
  2. File Restriction
    For security reasons, the worker thread cannot read local files, and the script it loads must come from the network and must be of the same origin as the script of the main thread
  3. DOM operations restrict
    the worker thread to run in another global context different from the window of the main thread, where the DOM object of the web page where the main thread is located cannot be read, and documentobjects such as , , windowetc. can be obtained, but browser APIs such as navigator, location(只读), , XMLHttpRequest, etc. can be obtained.setTimeout族
  4. Communication restrictions
    The worker thread and the main thread are not in the same context, so they cannot communicate directly, and need to postMessagecommunicate through methods.
  5. The script restricts
    the worker thread from executing alert, confirmbut can use XMLHttpRequestthe object to send an ajax request.

Description of Worker on MDN official website

Guess you like

Origin blog.csdn.net/bobo789456123/article/details/129311359