Web Workerをインラインで使う
HTML5 APIで追加されつつも、あまり使われている雰囲気がないのがWeb Workerではないでしょうか。使い方はそれほど難しい訳ではないですが、別途JavaScriptファイルを用意したりするのが面倒に感じられるのかも知れません。JavaScriptではできない、並列処理を行うためには必須のAPIです。
そこで手軽に使えるようにインラインのちょっとしたコードをWeb Worker化してみたいと思います。
サンプルのコード
例えば次のようなコードをWeb Worker化します。 e はメインスレッドから渡されるイベントで、 e.data でメッセージを受け取れます。メインスレッドからは onmessage が呼ばれますので、処理を行った上で postMessage で返せばOKです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
onmessage = (e) => { | |
setTimeout(() => { | |
postMessage('Workerからの返信です。' + e.data); | |
}, 2000); | |
} |
このコードを文字列にします。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const code = ` | |
onmessage = (e) => { | |
setTimeout(() => { | |
postMessage('Workerからの返信です。' + e.data); | |
}, 2000); | |
} | |
`; |
Blob化する
次にこの文字列をBlobにします。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const blob = new Blob([code]); | |
const blobURL = URL.createObjectURL(blob); |
ワーカーにする
後はこのblobURLをワーカーとして指定するだけです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const worker = new Worker(blobURL); |
これで準備完了です。
実行する
後はメインスレッドからpostMessageを使ってWeb Workerを呼び出します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
worker.postMessage("Execute"); |
逆にワーカー側からメッセージが来た時にはonmessageが呼ばれます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
worker.onmessage = (e) => { | |
alert(e.data); | |
}; |
このようにメインのJavaScriptファイルの中からWeb Workerを動的に作れるなら使い道があるかも知れません。なおWeb WorkerはDOM操作やwindow/documentオブジェクトへのアクセスができないので注意してください。ネットワークへのアクセスはできるので、バックグラウンドで通信を行うと言った時には良さそうです。
デモをJSFiddleにアップしてありますので参考にしてください。
コメントは受け付けていません。