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