Online Use | 中文 | Version Log | Feedback bug | Gitee
StringWorker is committed to helping developers access WebWorker at low cost. In webpack and rollup projects, js or ts modules are introduced as the internal code of the worker, and there is no need to maintain the internal code of the worker separately.
- Use the code string to initialize the worker without using a third-party url
- Support Promise to get the message returned by the worker
- Support webpack, rollup import loader use (under development...)
npm i string-worker
import StringWorker from 'string-worker';
<script src="https://cdn.jsdelivr.net/npm/string-worker/string-worker.min.js"></script>
<script>
window.StringWorker;
</script>
const worker = new StringWorker(/* javascript*/`
globalThis.addEventListener('message', function (e) {
var data = e.data;
// do something...
console.log('Worker Receive: ', data);
globalThis.postMessage('Worker Send: '+data);
}, false);
`);
worker.onMessage(data => {
console.log(data);
});
worker.postMessage('Hello World');
const worker = new StringWorker(/* javascript*/`
globalThis.addEventListener('message', function (e) {
var data = e.data;
console.log('Worker Receive: ', data);
// do something...
var message = 'Worker Send: '+data.message;
globalThis.postMessage({
message: message,
id: data.id
});
}, false);
`);
let id = 0;
worker.postMessage({
message: 'Hello World',
id: `msg_${id++}`, // need to pass in a unique id to match the message
}).then(d => {
console.log('Worker Return: ', d);
});
const worker = new StringWorker({
setup () { // not required
return {msg: 'hello world'};
},
onmessage (message, data) { // The second parameter is the return value of setup
return {receive: message.send + data.msg};
}
});
worker.postMessage({send: 'Hello'}).then(d => {
console.log(d);
});
When using ts references, generics can be passed in to standardize setup return values and message types
const worker = new StringWorker<
{msg: string}, // setup return value
{send: string}, // type of send
{receive: string} // return type
>({
setup () { // not required
return {msg: 'hello world'};
},
onmessage (message, data) { // The second parameter is the return value of setup
return {receive: message.send + data.msg};
}
});
worker.postMessage({send: 'Hello'}).then(d => {
console.log(d);
});
This part is currently under development. At present, developers can write an independent packaging module to package the worker code into a file, and then import the file as a StringWorker construction parameter to implement the loader function.