webWorker 开启javascript另外的线程

javascript是一个单线程语音,因此所有执行代码放在一个线程里面 因此javascriot是从上到小执行代码的,但是遇到大量切繁重的任务例如图形计算 请求,轮询等需要耗时的任务虽然可以使用异步来避免造成页面渲染的阻塞,但是异步任务完成后还要对数据进行处理因此也会导致页面的卡顿,因此可使用worker多开线程解决,让主线程专注于页面的交互和渲染,但是Workers不是越多越好,每个Worker都需要自己的运行环境,这会占用额外的内存;管理多个Worker增加了代码的复杂性,包括Worker的创建、销毁、通信以及错误处理等方面。

示例:一个worker发送两个不同的请求
index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Worker Example</title>
  </head>
  <body>
    <button id="fetch-students">获取学生列表</button>
    <button id="fetch-custom-data">获取自定义数据</button>

    <script>
      const worker = new Worker("worker.js");

      document
        .getElementById("fetch-students")
        .addEventListener("click", () => {
          // 发送消息给worker,指示需要获取学生列表
          worker.postMessage({ action: "studentList" });
        });

      document
        .getElementById("fetch-custom-data")
        .addEventListener("click", () => {
          // 发送消息给worker,指示需要获取自定义数据
          worker.postMessage({ action: "studentOne" });
        });

      worker.onmessage = function (e) {
        const message = e.data;
        if (message.type === "studentList") {
          console.log(message.data);
        } else if (message.type === "studentOne") {
          console.log(message.data);
        }
      };
    </script>
  </body>
</html>

worker
 

// 监听来自主线程的消息
onmessage = function (e) {
  if (e.data.action === "studentList") {
    fetch("http://localhost:5500/students")
      .then((response) => response.json()) // 假设我们期待JSON响应
      .then((data) => {
        // 将从服务器获取的数据发送回主线程,并附带类型信息
        self.postMessage({ type: "studentList", data: data });
      })
      .catch((error) => {
        self.postMessage({ type: "error", message: "请求失败" });
      });
  } else if (e.data.action === "studentOne") {
    fetch("http://localhost:5500/students/1")
      .then((response) => response.json()) // 假设我们期待JSON响应
      .then((data) => {
        // 将从服务器获取的数据发送回主线程,并附带类型信息
        self.postMessage({ type: "studentOne", data: data });
      })
      .catch((error) => {
        self.postMessage({ type: "error", message: "请求失败" });
      });
  }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值