Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update CrossOriginWorkerMaker to use cache #778

Merged
merged 1 commit into from
Mar 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions packages/kernel/src/cross-origin-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,26 @@
// so this `CrossOriginWorkerMaker` class must be defined in a separate file and
// be imported as the `Worker` alias into the file where the syntax is used to load the worker.
// This technique was introduced at https://github.com/webpack/webpack/discussions/14648#discussioncomment-1589272

const workerBlobUrlCache = new Map<string, string>();

function getWorkerBlobUrl(url: URL): string {
const urlStr = url.toString();

const cached = workerBlobUrlCache.get(urlStr);
if (cached) {
console.debug(`Using a cached worker blob URL for ${urlStr}`);
return cached;
}

const workerBlob = new Blob([`importScripts("${urlStr}");`], {
type: "text/javascript",
});
const workerBlobUrl = URL.createObjectURL(workerBlob);
workerBlobUrlCache.set(urlStr, workerBlobUrl);
return workerBlobUrl;
}

export class CrossOriginWorkerMaker {
public readonly worker: Worker;

Expand All @@ -18,12 +38,8 @@ export class CrossOriginWorkerMaker {
console.debug(
`Failed to load a worker script from ${url.toString()}. Trying to load a cross-origin worker...`
);
const workerBlob = new Blob([`importScripts("${url.toString()}");`], {
type: "text/javascript",
});
const workerBlobUrl = URL.createObjectURL(workerBlob);
const workerBlobUrl = getWorkerBlobUrl(url);
this.worker = new Worker(workerBlobUrl);
URL.revokeObjectURL(workerBlobUrl);
}
}
}
Loading