mirror of
https://github.com/glitch-soc/mastodon.git
synced 2025-12-16 01:09:55 +00:00
[Glitch] Enables cross-origin Web Workers
Port 7f9ad7eabf to glitch-soc
Signed-off-by: Claire <claire.github-309c@sitedethib.com>
This commit is contained in:
29
app/javascript/flavours/glitch/utils/workers.ts
Normal file
29
app/javascript/flavours/glitch/utils/workers.ts
Normal 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);
|
||||
}
|
||||
Reference in New Issue
Block a user