Data URLでWeb Workerを動かす
予めData URL形式にして読み込むようにすれば、いちいちworker codeをfetchすることなく、即workerを起動させることができるだろう
というわけで試してみる
worker codeをESModulesで記述する
Data URLに変換する
new Worker()にData URLを指定する
2021-06-27 11:03:26 成功した
code:js
import('/api/code/programming-notes/Data_URLでWeb_Workerを動かす/script.js');
code:script.js
import {src} from './workerSrc.js';
const worker = new Worker(src);
window.update = () => new Promise(resolve => {
worker.onmessage = () => resolve();
worker.postMessage({source: scrapbox.Project.pages.map(({title}) => title)});
});
window.search = query => new Promise(resolve => {
worker.onmessage = ({data}) => resolve(data);
worker.postMessage({query});
});
code:workerSrc.js
export const src='data:application/javascript;base64,KCgpPT57dmFyIHU9MjE0NzQ4MzY0OCxNPTY1NTM2LGw9W3UsMCwwLDBdLFQ9ZT0+ZT49NjUmJmU8PTkwLF89ZT0+ZT49OTcmJmU8PTEyMix3PWU9PlQoZSk/ZSszMjplLEk9ZT0+XyhlKT9lLTMyOmUsaD1lPT5lLnNwbGl0KCIiKS5tYXAocz0+cy5jaGFyQ29kZUF0KDApKTtmdW5jdGlvbiBtKGUpe2xldCBzPVsuLi5BcnJheShNKV0ubWFwKG89PjApLGk9MCx0PXU7Zm9yKGxldCBvIG9mIGgoZSkpbz09PTMyP2l8PXQ6KHNbb118PXQsc1tJKG8pXXw9dCxzW3cobyldfD10LHQ+Pj49MSk7bGV0IGc9dDtmdW5jdGlvbiBBKG89bCxwPSIiKXtsZXQgcj1vWzBdLG49b1sxXSxjPW9bMl0sYT1vWzNdO2ZvcihsZXQgayBvZiBoKHApKXQ9c1trXSxhPWEmaXwoYSZ0KT4+PjF8Yz4+PjF8YyxjPWMmaXwoYyZ0KT4+PjF8bj4+PjF8bixuPW4maXwobiZ0KT4+PjF8cj4+PjF8cixyPXImaXwociZ0KT4+PjEsbnw9cj4+PjEsY3w9bj4+PjEsYXw9Yz4+PjE7cmV0dXJuW3IsbixjLGFdfWZ1bmN0aW9uIGYobyxwPTApe2xldCByPUEobCxvKTtyZXR1cm4gcD49bC5sZW5ndGgmJihwPWwubGVuZ3RoLTEpLChyW3BdJmcpIT0wfXJldHVybiBmLnNvdXJjZT1lLGZ9dmFyIHg9W107c2VsZi5hZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIiwoe2RhdGE6ZX0pPT57aWYoZS5zb3VyY2Upe3g9ZS5zb3VyY2Usc2VsZi5wb3N0TWVzc2FnZSh7fSk7cmV0dXJufWxldCBzPW0oYCAke2UucXVlcnl9IGApLGk9TWF0aC5taW4oNCxNYXRoLmZsb29yKChlLnF1ZXJ5Lmxlbmd0aCsyKS80KSk7c2VsZi5wb3N0TWVzc2FnZSh4LmZpbHRlcih0PT5zKHQsaSkpKX0pO30pKCk7Cg==';
code:sh
code:build.ts
import {run} from '/api/code/takker/UserScriptをbundleするDeno_script/script.ts';
import {BlobToURI} from '/api/code/takker/BlobをData_URIに変換する/script.js';
const {outputFiles} = await run(
https://scrapbox.io/api/code/programming-notes/Data_URLでWeb_Workerを動かす/worker.js,
{},
{
charset: 'utf8',
bundle: true,
minify: true,
write: false, // 標準出力やfileにbundleしたコードを出力しない
format: 'iife',
}
);
const code = outputFiles?.0?.text ?? ''; const blob = new Blob(code, {type: 'application/javascript'}); console.log(export const src='${await BlobToURI(blob)}';);
code:worker.js
import {Asearch} from '../asearch@1.0.2/script.js';
let source = [];
self.addEventListener('message', ({data}) => {
if (data.source) {
source = data.source;
self.postMessage({});
return;
}
const match = Asearch( ${data.query} );
const ambig = Math.min(4, Math.floor((data.query.length + 2) / 4));
self.postMessage(source.filter(word => match(word, ambig)));
});
JavaScript.icon
Deno.icon