@78nine/sideworker 中文文档教程
SideWorker
SideWorker 是一个最小的 JavaScript 库,可以尽可能轻松地使用 Web Worker。
它基于 WorkerB 库,由 Luke Schaefer< /a>。
SideWorker 的主要目的是不必为在不同线程中运行的代码创建单独的文件。 Web Workers 可以内嵌到主代码中创建并异步通信。
这个想法是将单独的脚本和与该脚本交互的逻辑合并到一个 JS 对象中。
Usage
Installation
SideWorker 没有依赖项。 您可以通过 NPM 安装它:
npm install @79nine/SideWorker
然后在您的代码中使用它:
import SideWorker from '@78nine/sideworker' // ES Module style
// or
const SideWorker = require('@78nine/sideworker') // Node style
另一种选择是在您的项目中简单地包含 minified 文件(例如通过 UnPKG ):
<script src='https://unpkg.com/@78nine/sideworker'></script>
此选项将公开您网页上可用的全局 SideWorker
变量。
Usage example:
// Create a new, empty SideWorker
const worker = new SideWorker();
// Define a method that will be run later in your code. This method needs:
// A name -> 'countToX'
// A function it will perform
worker.define('countToX', (x) => {
for(let i = 0; i < x; i++) {
continue;
}
return i;
}
// Use the defined method where you need it, and handle it's result via Promise:
worker.run.countToX(42).then((res) => console.log('X is', res));
// or with async/await syntax
const res = await worker.run.countToX(128);
console.log('Now the X is', res);
// The method's operation is non-blocking and performed in a seperate thread.
Options:
创建 SideWorker 的实例时,您可以使用两个选项传递它和对象:
debug
默认值:false
如果 debug
选项将设置为 true
SideWorker 将为您提供一些有关它在浏览器控制台内工作的附加信息。
const worker = new SideWorker({ debug: true });
init
默认:未定义
init
选项可用于传递一个函数,该函数将在 Web Worker 创建时自动调用。 这对于 importScripts()
和定义稍后需要的 worker-scoped 变量或函数非常有用。
const worker = new SideWorker({
init: () => {
importScripts('https://unpkg.com/faker@5.5.3/dist/faker.min.js');
self.someGlobalFunction = () => {
// do something
}
}
});
// and then inside another method:
worker.define('doSomething', () => {
// `faker` is a globally available variable
// `someGlobalFunction()` is a globally available function
});
也可以将其他参数传递给主脚本范围内可用的 init 函数:
const answer = 42;
const persona = {
firstName: 'Arthur',
lastName: 'Dent'
}
const worker = new SideWorker({
init: (num, obj) => {
self.answer = num; // the `num` value is `42`
self.him = obj; // the `obj` value is `{ firstName: 'Arthur', lastName: 'Dent' }`
}
}, answer, persona);
注意:所有基本功能的示例也可以在 示例 中探索文件夹。
SideWorker
SideWorker is a minimal JavaScript library to make using Web Workers as painless as possible.
It has been based on the WorkerB library by Luke Schaefer.
The main purpose of SideWorker is NOT having to create a seperate file for code that is run in a different thread. The Web Workers can be created inline to the main code and be communicated with asynchronously.
The idea is to consolidate the seperate script and the logic to interact with that script into one JS object.
Usage
Installation
SideWorker has no dependencies. You can install it via NPM:
npm install @79nine/SideWorker
and then use it in your code:
import SideWorker from '@78nine/sideworker' // ES Module style
// or
const SideWorker = require('@78nine/sideworker') // Node style
Another option is to simply include the minified file in your project (e.g. through the UnPKG):
<script src='https://unpkg.com/@78nine/sideworker'></script>
This option will expose a global SideWorker
variable available on you web page.
Usage example:
// Create a new, empty SideWorker
const worker = new SideWorker();
// Define a method that will be run later in your code. This method needs:
// A name -> 'countToX'
// A function it will perform
worker.define('countToX', (x) => {
for(let i = 0; i < x; i++) {
continue;
}
return i;
}
// Use the defined method where you need it, and handle it's result via Promise:
worker.run.countToX(42).then((res) => console.log('X is', res));
// or with async/await syntax
const res = await worker.run.countToX(128);
console.log('Now the X is', res);
// The method's operation is non-blocking and performed in a seperate thread.
Options:
When creating an instance of the SideWorker you can pass it and object with two options:
debug
Default: false
If the debug
option will be set to true
the SideWorker will give you some additional information about it's work inside the browser's console.
const worker = new SideWorker({ debug: true });
init
Default: undefined
The init
option can be used to pass a function, which then will be automatically called upon the Web Worker's creation. This can be very useful for instance to importScripts()
and define worker-scoped variables or function needed later.
const worker = new SideWorker({
init: () => {
importScripts('https://unpkg.com/faker@5.5.3/dist/faker.min.js');
self.someGlobalFunction = () => {
// do something
}
}
});
// and then inside another method:
worker.define('doSomething', () => {
// `faker` is a globally available variable
// `someGlobalFunction()` is a globally available function
});
It is also possible to pass additional arguments to the init function that are available in your main script's scope:
const answer = 42;
const persona = {
firstName: 'Arthur',
lastName: 'Dent'
}
const worker = new SideWorker({
init: (num, obj) => {
self.answer = num; // the `num` value is `42`
self.him = obj; // the `obj` value is `{ firstName: 'Arthur', lastName: 'Dent' }`
}
}, answer, persona);
Note: examples of all the basic functionality can be also explored in the examples folder.