blob: 4ae41ff0ee1a15deec546dacd80b7cdac56db1bd [file] [log] [blame]
Ben Rohlfs25de6c02022-02-01 12:47:16 +01001/**
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 Rohlfsfb573ab2022-02-07 12:53:08 +010013function wrapUrl(url: string) {
Ben Rohlfs25de6c02022-02-01 12:47:16 +010014 const content = `importScripts("${url}");`;
15 return URL.createObjectURL(new Blob([content], {type: 'text/javascript'}));
16}
Ben Rohlfsfb573ab2022-02-07 12:53:08 +010017
18export function createWorker(workerUrl: string): Worker {
Ben Rohlfs27915682022-03-17 17:09:53 +010019 if (!workerUrl.startsWith('http'))
20 throw new Error(`Worker URL '${workerUrl}' does not start with 'http'.`);
Ben Rohlfsfb573ab2022-02-07 12:53:08 +010021 return new Worker(wrapUrl(workerUrl));
22}
Ben Rohlfs168a2692022-02-08 12:47:45 +010023
24export function importScript(scope: WorkerGlobalScope, url: string): void {
25 scope.importScripts(url);
26}