Ben Rohlfs | 25de6c0 | 2022-02-01 12:47:16 +0100 | [diff] [blame] | 1 | /** |
| 2 | * @license |
| 3 | * Copyright 2022 Google LLC |
| 4 | * SPDX-License-Identifier: Apache-2.0 |
| 5 | */ |
| 6 | |
| 7 | /** |
| 8 | * We cannot import the worker script from cdn directly, because that is |
| 9 | * creating cross-origin issues. Instead we have to create a worker script on |
| 10 | * the fly and pull the actual worker via `importScripts()`. Apparently that |
| 11 | * is a well established pattern. |
| 12 | */ |
Ben Rohlfs | fb573ab | 2022-02-07 12:53:08 +0100 | [diff] [blame] | 13 | function wrapUrl(url: string) { |
Ben Rohlfs | 25de6c0 | 2022-02-01 12:47:16 +0100 | [diff] [blame] | 14 | const content = `importScripts("${url}");`; |
| 15 | return URL.createObjectURL(new Blob([content], {type: 'text/javascript'})); |
| 16 | } |
Ben Rohlfs | fb573ab | 2022-02-07 12:53:08 +0100 | [diff] [blame] | 17 | |
| 18 | export function createWorker(workerUrl: string): Worker { |
Ben Rohlfs | 2791568 | 2022-03-17 17:09:53 +0100 | [diff] [blame] | 19 | if (!workerUrl.startsWith('http')) |
| 20 | throw new Error(`Worker URL '${workerUrl}' does not start with 'http'.`); |
Ben Rohlfs | fb573ab | 2022-02-07 12:53:08 +0100 | [diff] [blame] | 21 | return new Worker(wrapUrl(workerUrl)); |
| 22 | } |
Ben Rohlfs | 168a269 | 2022-02-08 12:47:45 +0100 | [diff] [blame] | 23 | |
| 24 | export function importScript(scope: WorkerGlobalScope, url: string): void { |
| 25 | scope.importScripts(url); |
| 26 | } |