填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

用 Web Worker 處理後臺程序

Background processing using web workers

Web Worker允許你在後臺執行緒中執行 CPU 密集型計算,解放主執行緒以更新使用者介面。如果你發現你的應用會進行很多計算,比如產生 CAD 圖紙或進行繁重的幾何計算,那麼使用 Web Worker 可以幫助你提高應用的效能。

Web workers allow you to run CPU-intensive computations in a background thread, freeing the main thread to update the user interface. If you find your application performs a lot of computations, such as generating CAD drawings or doing heavy geometrical calculations, using web workers can help increase your application's performance.

CLI 不支援在 Web Worker 中執行 Angular。

The CLI does not support running Angular itself in a web worker.

新增一個 Web Worker

Adding a web worker

要把 Web Worker 新增到現有專案中,請使用 Angular CLI ng generate 命令。

To add a web worker to an existing project, use the Angular CLI ng generate command.

ng generate web-worker <location>
      
      ng generate web-worker <location>
    

你可以在應用的任何位置新增 Web Worker。例如,要把一個 Web Worker 新增到根元件 src/app/app.component.ts,請執行如下命令。

You can add a web worker anywhere in your application. For example, to add a web worker to the root component, src/app/app.component.ts, run the following command.

ng generate web-worker app
      
      ng generate web-worker app
    

該命令會執行以下操作。

The command performs the following actions.

  • 把你的專案配置為使用 Web Worker,如果還沒有的話。

    Configures your project to use web workers, if it isn't already.

  • 把如下腳手架程式碼新增到 src/app/app.worker.ts 以接收訊息。

    Adds the following scaffold code to src/app/app.worker.ts to receive messages.

    addEventListener('message', ({ data }) => { const response = `worker response to ${data}`; postMessage(response); });
    src/app/app.worker.ts
          
          addEventListener('message', ({ data }) => {
      const response = `worker response to ${data}`;
      postMessage(response);
    });
        
  • 把如下腳手架程式碼新增到 src/app/app.component.ts 以使用這個 Worker。

    Adds the following scaffold code to src/app/app.component.ts to use the worker.

    if (typeof Worker !== 'undefined') { // Create a new const worker = new Worker('./app.worker', { type: 'module' }); worker.onmessage = ({ data }) => { console.log(`page got message: ${data}`); }; worker.postMessage('hello'); } else { // Web workers are not supported in this environment. // You should add a fallback so that your program still executes correctly. }
    src/app/app.component.ts
          
          if (typeof Worker !== 'undefined') {
      // Create a new
      const worker = new Worker('./app.worker', { type: 'module' });
      worker.onmessage = ({ data }) => {
        console.log(`page got message: ${data}`);
      };
      worker.postMessage('hello');
    } else {
      // Web workers are not supported in this environment.
      // You should add a fallback so that your program still executes correctly.
    }
        

產生這個初始腳手架之後,你必須把程式碼重構成向這個 Worker 傳送訊息和從 Worker 接收訊息,以便使用 Web Worker。

After you generate this initial scaffold, you must refactor your code to use the web worker by sending messages to and from the worker.

某些環境或平臺(比如伺服器端渲染中使用的 @angular/platform-server 不支援 Web Worker。為了確保你的應用能夠在這些環境中工作,你必須提供一個回退機制來執行本來要由這個 Worker 執行的計算。

Some environments or platforms, such as @angular/platform-server used in Server-side Rendering, don't support web workers. To ensure that your application will work in these environments, you must provide a fallback mechanism to perform the computations that the worker would otherwise perform.