Skip to content

Commit

Permalink
add loadScript to Analytics
Browse files Browse the repository at this point in the history
  • Loading branch information
ugran committed Jun 5, 2024
1 parent a2b4653 commit 16f98c0
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions packages/browser/src/core/analytics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,63 @@ export class Analytics
return this._universalStorage
}

loadScript(
src: string,
attributes?: Record<string, string>
): Promise<HTMLScriptElement> {
function findScript(src: string): HTMLScriptElement | undefined {
const scripts = Array.prototype.slice.call(
window.document.querySelectorAll('script')
)
return scripts.find((s) => s.src === src)
}

const found = findScript(src)

if (found !== undefined) {
const status = found?.getAttribute('status')

if (status === 'loaded') {
return Promise.resolve(found)
}

if (status === 'loading') {
return new Promise((resolve, reject) => {
found.addEventListener('load', () => resolve(found))
found.addEventListener('error', (err) => reject(err))
})
}
}

return new Promise((resolve, reject) => {
const script = window.document.createElement('script')

script.type = 'text/javascript'
script.src = src
script.async = true

script.setAttribute('status', 'loading')
for (const [k, v] of Object.entries(attributes ?? {})) {
script.setAttribute(k, v)
}

script.onload = (): void => {
script.onerror = script.onload = null
script.setAttribute('status', 'loaded')
resolve(script)
}

script.onerror = (): void => {
script.onerror = script.onload = null
script.setAttribute('status', 'error')
reject(new Error(`Failed to load ${src}`))
}

const tag = window.document.getElementsByTagName('script')[0]
tag.parentElement?.insertBefore(script, tag)
})
}

async track(...args: EventParams): Promise<DispatchedEvent> {
const [name, data, opts, cb] = resolveArguments(...args)

Expand Down

0 comments on commit 16f98c0

Please sign in to comment.