官术网_书友最值得收藏!

Building a basic web worker

Once we have the app created and instantiated, we will create the worker.js file first using the following commands from the root of your app:

cd src/app
mkdir utils
touch worker.js

This will generate the utils folder and the worker.js file in it.

Note the following two things here:

  • It is a simple JS file and not a TypeScript file, even though the entire application is in TypeScript
  • It is called worker.jswhich means that we will be creating a web worker for the parsing and evaluation that we are about to perform

Web workers are used to simulate the concept of multithreading in JavaScript, which is usually not the case. Also, since this thread runs in isolation, there is no way for us to provide dependencies to that. This works out very well for us because our main app is only going to accept the user's input and provide it to the worker on every key stroke while it's the responsibility of the worker to evaluate this expression and return the result or the error if necessary.

Since this is an external file and not a standard Angular file, we will have to load it up as an external script so that our application can use it subsequently. To do so, open your .angular-cli.json file and update the scripts option to look as follows:

...
"scripts"
: [
"app/utils/worker.js"
],
...

Now, we will be able to use the injected worker, as follows:

this.worker = new Worker('scripts.bundle.js');

First, we will add the necessary changes to the app.component.ts file so that it can interact with worker.js as needed. 

主站蜘蛛池模板: 景东| 安宁市| 阿拉善左旗| 绥江县| 桂平市| 扎赉特旗| 丰镇市| 于田县| 固始县| 上高县| 竹溪县| 铜山县| 阿鲁科尔沁旗| 琼结县| 南安市| 黑龙江省| 吴忠市| 崇义县| 竹北市| 曲阜市| 西青区| 舟山市| 崇州市| 汝州市| 卓资县| 利辛县| 东辽县| 宝丰县| 泰兴市| 长乐市| 阳西县| 泰来县| 蓬莱市| 昭觉县| 平顶山市| 开平市| 颍上县| 龙江县| 忻城县| 山丹县| 安宁市|