1
头图

foreword

Hello everyone, I am a forest three hearts, the most easy to understand the words of the hardest knowledge is my motto, is based on the premise advanced is the beginning of my heart today to tell you a familiar and Stranger Things - Web Worker

Why is js a single threaded language?

Let me tell you why JavaScript is a single-threaded language? We all know that JavaScript is a front-end-based language, and the front-end stage is the browser, and what does the browser do to please users? What is passed is a page composed of DOM nodes one by one. Therefore, the ultimate goal of JavaScript is to display the quality of the page.

1641539889(1).jpg

JavaScript is designed as a single-threaded language for pages. Let’s assume that JavaScript is a multi-threaded language. If one day, thread 1 is modifying the DOM node, and thread 2 is also modifying the same DOM node, then who should the page listen to? This will cause conflicts, which are not allowed in front of the user, so JavaScript is designed as a single-threaded language, and what you want to do must be done in order.

Web Worker?

background

Just said that JavaScript is a single-threaded language, which also caused many problems. I don’t know if you have encountered such a thing when you usually develop: processing a super large data, causing the logic of the entire code to be blocked for a period of time

1641539197(1).png

Let me tell you what happened to me:

  • 1. When hashing a large file slice, it needs to be processed for a short period of time.
  • 2. When front-end processing of tree data, it takes a short period of time to process
    suspended animation problem might this lead to?
  • 1. Blocking of page rendering
  • 2. Blocking of code execution behind

what is it?

Web Worker is a new technology bred to solve the problem of browser suspended animation. It is a multi-threaded model and is also host-based. It belongs to a sub-thread in the JavaScript thread, which is completely controlled by the main thread, but cannot operate the DOM Web Worker The uniqueness of the DOM needs to be guaranteed, so the main tone cannot be changed, but a new thread is required to share the complicated computing tasks, which is Web Worker

1641543329(1).jpg

compatibility:

image.png

Web Worker has the following features:

  • 1. Once created, it will not be interrupted by the main thread. Even if the main thread is stuck, the Web Worker is still running
  • 2. Web Worker is also restricted by the same-origin policy, and only the same-origin web pages can be accessed
  • 3. You cannot operate and access the DOM. As mentioned earlier, multi-threaded operation of the DOM is easy to cause conflicts, so it is forbidden to
  • 4. Global interaction methods (alert, confirm, etc.) cannot be used, and other global methods can basically be used
  • 5. Cannot read local files (in fact, the browser itself prohibits JavaScript from reading local files, for security reasons)
  • 6. The worker thread and the main thread do not share scope and resources
  • 7. There are two types of Web Workers:

    • Dedicated Web Worker : dedicated thread, this thread can only be used in one web page
    • Shared Web Worker : Shared thread, which can be shared among multiple web pages of the same origin, and is also one of the means of cross-page communication

Using Web Workers

Scenes

In order to let everyone see Web Worker , I created several new files

// index.html
<script src="./index.js"></script>
<img src="./头像.jpg" alt="">
// index.js

console.time('处理数据时间')

// 模拟数据处理
function handleData(num) {
  for (let i = 0; i < num; i++) {
    let str = ''
    while (str.length < 150) {
      str += '哈'
    }
  }
}

handleData(2000000)
console.timeEnd('处理数据时间')

We can see how much time it took to process the data:

1641542381(1).jpg

And the rendering of the picture is also after this time (it also takes a certain time to render the picture, so there is a difference), which also shows that the data processing just now blocked the rendering of the page:

1641547112(1).jpg

Basic use of Web Worker

Dedicated Web Worker used in project development, there are many, so let’s talk about the basic use of this

Rewrite the code in index.js

// index.js

// 实例一个 Woeker ,并传入目标文件路径,这个目标文件将会生成一个worker线程
const worker = new Worker("data.js")
// 使用 postMessage 传输信息到目标文件
worker.postMessage(2000000)
// 使用 onmessage 接受信息
worker.onmessage = (e) => {
  console.log(e.data)
};
// 使用 onerror 进行目标文件,也就是指定worker线程发生错误时的回调
worker.onerror = function (e) {
  console.log("error at " + e.filename + ":" + e.lineno + e.message)
};

Then we create the target file data.js , which will generate a worker thread

// 使用 importScripts 进行文件的引用,可引用 url、本地js文件
importScripts('xxxxxxx')
// importScripts('xxxxxxx', 'xxxxxxxx') 也可以传多个

// 模拟数据处理
function handleData(num) {
  for (let i = 0; i < num; i++) {
    let str = ''
    while (str.length < 150) {
      str += '哈'
    }
  }
}

onmessage = async (e) => {
  console.time('处理数据时间')
  const res = handleData(e.data)
  postMessage('处理完了')
  console.timeEnd('处理数据时间')
}

Effect

Let's take a look at the code and rendering effect, and compare it with the beginning:

1641546740(1).jpg

Image rendering is also not blocked:

1641546979(1).jpg

cancel process

The process can be terminate

worker.onmessage = (e) => {
  // 报错时马上终止指定worker进程
  worker.terminate()
  console.log(e.data)
}

personal understanding

In fact, Web Worker does not essentially change the fact that JavaScript is single-threaded on the multi-threading of the 161e62631819bf browser

Epilogue

I'm Lin Sanxin, an enthusiastic front-end rookie programmer. If you are motivated, like the front-end, and want to learn the front-end, then we can make friends and fish together haha, touch the fish group, add me, please note [Si No]

image.png


Sunshine_Lin
2.1k 声望7.1k 粉丝