Enables cross-origin Web Workers (#35483)

This commit is contained in:
Echo authored and GitHub committed 2025-07-24 07:14:27 +00:00
1 parent a6794c066d
commit 7f9ad7eabf
5 files changed
+44 -6

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
/**
* Loads Web Worker that is compatible with cross-origin scripts for CDNs.
*
* Returns null if the environment doesn't support web workers.
*/
export function loadWorker(url: string | URL, options: WorkerOptions = {}) {
if (!('Worker' in window)) {
return null;
}
try {
// Check if the script origin and the window origin are the same.
const scriptUrl = new URL(import.meta.url);
if (location.origin === scriptUrl.origin) {
// Not cross-origin, can just load normally.
return new Worker(url, options);
}
} catch (err) {
// In case the URL parsing fails.
console.warn('Error instantiating Worker:', err);
}
// Import the worker script from a same-origin Blob.
const contents = `import ${JSON.stringify(url)};`;
const blob = URL.createObjectURL(
new Blob([contents], { type: 'text/javascript' }),
);
return new Worker(blob, options);
}