Help us understand the problem. What is going on with this article?

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

参考: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

以上です。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした