Skip to content

Commit d17319a

Browse files
authored
Enable use of Tools.LoadScript in a WebWorker (#12884)
* use importScripts instead of HTMLScriptElement when LoadScript is invoked in a WebWorker * lint
1 parent 3295562 commit d17319a

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

packages/dev/core/src/LibDeclarations/browser.d.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ interface Window {
2222
setImmediate(handler: (...args: any[]) => void): number;
2323
}
2424

25+
interface WorkerGlobalScope {
26+
importScripts: (...args: string[]) => void;
27+
}
28+
29+
type WorkerSelf = WindowOrWorkerGlobalScope & WorkerGlobalScope;
30+
2531
interface HTMLCanvasElement {
2632
requestPointerLock(): void;
2733
msRequestPointerLock?(): void;

packages/dev/core/src/Misc/tools.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,16 @@ export class Tools {
416416
* @param scriptId defines the id of the script element
417417
*/
418418
public static LoadScript(scriptUrl: string, onSuccess: () => void, onError?: (message?: string, exception?: any) => void, scriptId?: string) {
419-
if (!IsWindowObjectExist()) {
419+
if (typeof (self as unknown as WorkerSelf).importScripts === "function") {
420+
try {
421+
(self as unknown as WorkerSelf).importScripts(scriptUrl);
422+
onSuccess();
423+
} catch (e) {
424+
onError?.(`Unable to load script '${scriptUrl}' in worker`, e);
425+
}
426+
return;
427+
} else if (!IsWindowObjectExist()) {
428+
onError?.(`Cannot load script '${scriptUrl}' outside of a window or a worker`);
420429
return;
421430
}
422431
const head = document.getElementsByTagName("head")[0];

0 commit comments

Comments
 (0)