gpt4 book ai didi

javascript - 如何使用 blob 创建 SharedWorker?

转载 作者:行者123 更新时间:2023-11-29 10:28:07 28 4
gpt4 key购买 nike

我想创建一个 SharedWorker,如一本优秀书籍的一章所述:https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch5.md

我能够为普通 web worker 编写一个非常好的示例:

function createAsker(limit) {
var blob = new Blob(["onmessage = function(e) { " +
"if (self.higher === undefined) self.higher = " + limit + "; " +
"if (self.lower === undefined) self.lower = 1;" +
"if (e.data === 'correct') { " +
"postMessage('Party time'); " +
"} else {" +
"if (e.data === 'greater') self.lower = parseInt((self.lower + self.higher) / 2);" +
"if (e.data === 'lower') self.higher = parseInt((self.lower + self.higher) / 2);" +
"postMessage(parseInt((self.lower + self.higher) / 2));" +
"}" +
"}"]);
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
return worker;
}

var asker = createAsker(1000);

function createAnswerer(limit) {
var blob = new Blob(["onmessage = function(e) { " +
"postMessage((e.data == " + limit + ") ? 'correct' : ((e.data < " + limit + ") ? 'greater' : 'lower'));" +
"}"]);
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
return worker;
}

var answerer = createAnswerer(42);

asker.onmessage = function(e) {
console.log('Asker says: ' + e.data);
if (e.data !== "Party time") {
setTimeout(function() {answerer.postMessage(e.data)}, 1000);
}
};

answerer.onmessage = function(e) {
console.log('Answerer says: ' + e.data);
setTimeout(function() {asker.postMessage(e.data)}, 1000);
};

asker.postMessage('start');

然而,我在创建共享 worker 时遇到了困难。我试图用这段代码创建一个:

function createWorker() {
var blob = new Blob(['addEventListener( "connect", function(evt){ ' +
'var port = evt.ports[0]; ' +
'port.addEventListener( "message", function(evt){' +
'port.postMessage( .. );debugger;' +
'} );' +
'port.start();' +
'} );']);
var blobURL = window.URL.createObjectURL(blob);
var w = new SharedWorker(blobURL);
return w;
}

var w = createWorker();

w.port.start();

w.port.onmessage = function(e) {
console.log(e.data);
};

w.port.onmessage('foobar');

在发送 foobar 的消息后,我希望我的共享 worker 发布一条消息,或者至少我希望调试器将其引导到代码中,但是,当我运行这段代码时,控制台会给出两个未定义的响应。

最佳答案

Base64 编码给出了一个永久的 URL,直到源代码发生变化。

const source = 'importScript("https://anotherhost/worker.js")';
const url = 'data:application/javascript;base64,' + btoa(source);
const worker = new SharedWorker(url);

它至少适用于 Chrome 73 和 Firefox 66。

有一个limit to the length大约 65 KB 的编码 URL。

关于javascript - 如何使用 blob 创建 SharedWorker?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53360329/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com