How to start the background thread of the browser with JavaScript?

1, Introduction

The worker object is used to create an independent background thread, which can handle some time-consuming operations without blocking the main thread (usually the UI thread). Available workers include: dedicated worker, shared worker and Service Worker.

2, Dedicated worker

Background threads can only be created by a single script call. However, in the worker, you cannot directly operate the DOM node or use the default methods and properties of the window object, Available methods and objects, look here!

1. worker instance

Create a work thread and communicate with the main thread. Between the main thread and the worker thread, the message is sent through postMessage() and received with onmessage.

<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset="utf-8">
    <title>work</title>
</head>
<body>
    <h1>Click the button to work Send message!</h1>
    <button id="number">click</button>
    <script>
        // 1. Create a work thread and a processing function to receive work information
        const myWorker = new Worker('worker.js');
        myWorker.onmessage = function (e) {
            alert(e.data);
        }

        // 2. Send message to work thread
        const btn = document.querySelector('#number');
        btn.onclick = function () {
            myWorker.postMessage("btn click");
        }
    </script>
</body>
</html>
// worker.js
// 3. Receive message
onmessage = function (e) {
    const workerResult = e.data + " : worker send";
    // 4. Send message to main thread
    postMessage(workerResult);
}
2,DedicatedWorkerGlobalScope

The global object of the dedicated worker can also be accessed by self.

3, SharedWorker

It can be called by multiple scripts and create multiple background threads, provided that the pages where these scripts are located must be of the same origin (the same protocol, host and port).

1. Simple example

Create a SharedWorker thread and communicate with the main thread.

<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset="utf-8">
    <title>work</title>
</head>
<body>
    <h1>Click the button to work Send message!</h1>
    <button id="number">click</button>
    <script>
        if (!!window.SharedWorker) {
            // 1. Create a sharedwork thread and a processing function to receive sharedwork information
            const myWorker = new SharedWorker('worker.js');
            myWorker.port.onmessage = function (e) {
                alert(e.data);
                console.log('Message received from worker');
            }

            // 2. Send information to sharedwork thread
            const btn = document.querySelector('#number');
            btn.onclick = function () {
                myWorker.port.postMessage("btn click");
                console.log('Message posted to worker');
            }
        } else {
            console.log("This browser does not support SharedWorker !")
        }
    </script>
</body>
</html>
// worker.js
// 3. Message processing function
onconnect = function (e) {
    var port = e.ports[0];

    port.onmessage = function (e) {
        var workerResult = e.data + " : worker send";
        // 4. Send message to main thread
        port.postMessage(workerResult);
    }

}
2,SharedWorkerGlobalScope

The global object of the shared worker can also be accessed by self.

4, Service Worker

Service workers essentially act as a proxy server between Web applications, browsers and the network (when available). This API is designed to create an effective offline experience. It intercepts network requests and updates resources from the server according to whether the network can be used to take appropriate actions. It also provides a portal to push notifications and access the background synchronization API.

Service workers can only be used for https, not for the stealth mode of Firefox browser.

Promise is widely used by Service workers because they usually wait for a response and return a successful or failed operation according to the response. Promise is perfect for this scenario.

At present, only Chrome and Firefox have relatively complete support for this function, which is not supported by other browsers for the time being.

5, Reference documents

Keywords: Javascript

Added by joviyach on Wed, 29 Dec 2021 07:15:11 +0200