3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Web Workerを別ファイルにしないでインラインスクリプトで実行する方法

Posted at

参考:The Basics of Web Workers - HTML5 Rocks

こちらの参考で知ったので、そのまま試してみたという内容になります。よろしくお願いいたします。:bow:

index.html
<!DOCTYPE html>
<meta charset="UTF-8">
<title>Document</title>

<script id="worker1" type="javascript/worker">
self.addEventListener("message", e => {
    self.postMessage(`${e.data} from worker!`);
});
</script>

<script>
const blob = new Blob([document.querySelector('#worker1').textContent]);
const worker = new Worker(window.URL.createObjectURL(blob));

worker.addEventListener("message", e => {
    console.log("Received: " + e.data);
});

worker.postMessage("hello");
</script>
Screen Shot 2020-02-09 at 16.07.39.png

workerファイルを別ファイルにすることなく実行することができました


window.URL.createObjectURL(blob) でBlobオブジェクトに保存されたデータを参照するためのURL文字列を作成できるので、それを別ファイル扱いにして読み込めるらしいです。

const blob = new Blob([document.querySelector('#worker1').textContent]);
console.log(window.URL.createObjectURL(blob)); // "blob:http://127.0.0.1:8000/a9a7fcfe-5952-49f1-a088-1835a6d0e872"
Screen Shot 2020-02-09 at 16.14.33.png

以上です。

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?