0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Web Workersとは

  • messageイベントでハンドル
  • UIをブロッキングせずに別スレッドで処理
  • ページに依存して終了

postMessageで値を渡す

worker.postMessage({type: 'initialLoaded', resText: 'Loaded!!!!'})

これは、コールバック内のdataにバインディングされる

(event) => {
  console.log(event.data.type); // initialLoaded
  console.log(event.data.resText); // Loaded
}

コード

コンストラクト

index.html
worker = new Worker(`worker.js`, {type: 'module'})

messageイベントに対しコールバック追加

index.html
worker.addEventListener("message", (event) => {})

worker.js側は、selfがWorkerインスタンス

worker.js
self.addEventListener("message", (event) => {})

message

worker.postMessage({type: 'initialLoaded', resText: 'Loaded!!!!'})

記述のコツ

postMessageでtypeという共通のpropertyを渡し、typeごとにswitch/caseする。

index.html
let worker;
function onLoad(event) {
  worker = new Worker("worker.js", { type: "module" }); // { type: "module"}でES moduleとして読み込み 
  worker.addEventListener("message", (event) => {
    switch (event.data.type){
      case "finishedCalculation":
        console.log(event.data.calcResult);
        break;
      default:
        console.error(`Unknown message '${event.data.type}'.`);
    }
  });
  worker.postMessage({type: "loaded", loadText: "worker"})
}
window.addEventListener("DOMContentLoaded", onLoad, false);

function handleClick(event) {
  if (!worker) return;
  worker.postMessage({type: "calculationStart"});
};
worker.js
self.addEventListener("message", async (event) => {
	switch (event.data.type) {
    case "loaded":
      console.log(`Hellow, ${event.data.loadText}!`);
      break;
    case "calculationStart":
      await new Promise(resolve => setTimeout(resolve, 2000));
      self.postMessage({
        type: "finishedCalculation",
        calcResult: Math.random().toString()
      });
      break;
    default:
      console.error(`Unknown message '${event.data.type}'.`);
  }
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?