Line data Source code
1 : /** Keep in sync with packages/shared-frontend-utils/src/loadExternalScript.ts. */
2 13 : const POLL_INTERVAL_MS = 50
3 :
4 : /**
5 : * Returns a singleton loader for an external script. `getReady` should return
6 : * the resolved value when the script's global is available, or `null` when not.
7 : * The returned function caches the in-flight Promise so concurrent callers share
8 : * one load, and resets on failure so a later caller can retry.
9 : */
10 13 : export function createScriptLoader<T>(
11 : src: string,
12 : getReady: () => T | null,
13 : timeoutMs = 10_000
14 : ): () => Promise<T> {
15 13 : let scriptPromise: Promise<T> | null = null
16 :
17 13 : return function loadScript(): Promise<T> {
18 0 : if (scriptPromise) return scriptPromise
19 :
20 0 : scriptPromise = new Promise<T>((resolve, reject) => {
21 0 : let settled = false
22 0 : let cancelPoll: (() => void) | undefined
23 :
24 0 : function trySettle(fn: () => void) {
25 0 : if (settled) return
26 0 : settled = true
27 0 : fn()
28 : }
29 :
30 0 : const ready = getReady()
31 0 : if (ready !== null) {
32 0 : resolve(ready)
33 0 : return
34 : }
35 :
36 0 : const existing = document.querySelector<HTMLScriptElement>(
37 : `script[src="${src}"]`
38 : )
39 :
40 0 : function startPoll(onSuccess: () => void): () => void {
41 0 : const pollId = window.setInterval(() => {
42 0 : const value = getReady()
43 0 : if (value !== null) {
44 0 : window.clearInterval(pollId)
45 0 : onSuccess()
46 0 : trySettle(() => resolve(value))
47 : }
48 : }, POLL_INTERVAL_MS)
49 0 : return () => window.clearInterval(pollId)
50 : }
51 :
52 0 : if (existing) {
53 : // load/error may have already fired on the pre-existing tag; poll for readiness
54 0 : const timeoutId = window.setTimeout(() => {
55 0 : cancelPoll?.()
56 0 : trySettle(() => {
57 0 : scriptPromise = null
58 0 : reject(new Error(`Script load timed out: ${src}`))
59 : })
60 : }, timeoutMs)
61 0 : cancelPoll = startPoll(() => window.clearTimeout(timeoutId))
62 0 : return
63 : }
64 :
65 0 : const scriptEl = document.createElement('script')
66 :
67 0 : const timeoutId = window.setTimeout(() => {
68 0 : cancelPoll?.()
69 0 : scriptEl.remove()
70 0 : trySettle(() => {
71 0 : scriptPromise = null
72 0 : reject(new Error(`Script load timed out: ${src}`))
73 : })
74 : }, timeoutMs)
75 :
76 0 : scriptEl.addEventListener(
77 : 'load',
78 : () => {
79 0 : if (settled) return
80 0 : const value = getReady()
81 0 : if (value !== null) {
82 0 : window.clearTimeout(timeoutId)
83 0 : trySettle(() => resolve(value))
84 : } else {
85 : // global may arrive asynchronously after load; poll under the shared timeout
86 0 : cancelPoll = startPoll(() => window.clearTimeout(timeoutId))
87 : }
88 : },
89 : { once: true }
90 : )
91 0 : scriptEl.addEventListener(
92 : 'error',
93 : () => {
94 0 : window.clearTimeout(timeoutId)
95 0 : scriptEl.remove()
96 0 : trySettle(() => {
97 0 : scriptPromise = null
98 0 : reject(new Error(`Script failed to load: ${src}`))
99 : })
100 : },
101 : { once: true }
102 : )
103 :
104 0 : scriptEl.src = src
105 0 : scriptEl.async = true
106 0 : document.head.appendChild(scriptEl)
107 : })
108 :
109 0 : return scriptPromise
110 : }
111 : }
|