Vorrei passare una funzione (o funzioni) tramite postMessage() a un web worker, perché non posso fare riferimento a file regolari.Come passare le funzioni a JavaScript Web Worker
Per disattivare il web worker, sto passando un URL oggetto (creato da un BLOB) al costruttore Worker. Quindi sto trasmettendo un messaggio, ma finora non ho avuto fortuna a inserire una funzione nel messaggio. Il messaggio (JSON) non può contenere direttamente le funzioni (come stabilito here) e sebbene importScripts sia teoricamente consentito, non ho avuto alcun successo nell'usarlo finora in Chrome o Firefox.
Il corpo del file html:
<div id="divText">1234</div>
<script>
var greeter = function greet(name) {
return "hello " + name;
};
function webWorkerWorker() {
self.postMessage("started1");
self.onmessage = function(event) {
importScripts(event.data.content);
self.postMessage("importScripts success");
var result = greeter("john");
self.postMessage(result);
};
}
var functionBody = mylib.extractFunctionBody(webWorkerWorker);
var functionBlob = mylib.createBlob([functionBody]);
var functionUrl = mylib.createObjectURL(functionBlob);
var functionBody2 = mylib.extractFunctionBody(greeter);
var functionBlob2 = mylib.createBlob([greeter]);
var functionUrl2 = mylib.createObjectURL(functionBlob2);
var worker = new Worker(functionUrl);
worker.onmessage = function(event) {
document.getElementById("divText").innerHTML = event.data;
}
worker.postMessage({
type: "init",
content: functionUrl2
});
</script>
Attualmente il risultato e l'impostazione del valore divText a "importScripts successo".
Sto facendo qualcosa di sbagliato? C'è un altro modo in cui le funzioni possono essere passate ai web worker? O non è possibile?
Hi è possibile fornire le funzioni "mylib" si utilizza here..Thanks – Buzz