61 lines
1.7 KiB
TypeScript
61 lines
1.7 KiB
TypeScript
import type {
|
|
SgsMapSDKConstructor
|
|
} from '@/types/sgs-map-sdk'
|
|
|
|
let loadingScriptUrl = ''
|
|
let loadRequest: Promise<SgsMapSDKConstructor> | null = null
|
|
|
|
const findExistingScript = (scriptUrl: string) => (
|
|
Array.from(document.scripts).find((script) => script.src.endsWith(scriptUrl) || script.getAttribute('src') === scriptUrl)
|
|
)
|
|
|
|
export const loadSgsMapScript = (scriptUrl: string): Promise<SgsMapSDKConstructor> => {
|
|
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
|
return Promise.reject(new Error('SGS Map SDK 只能在 H5 浏览器环境中加载'))
|
|
}
|
|
|
|
if (window.SGSMapSDK) {
|
|
return Promise.resolve(window.SGSMapSDK)
|
|
}
|
|
|
|
if (loadRequest && loadingScriptUrl === scriptUrl) {
|
|
return loadRequest
|
|
}
|
|
|
|
loadingScriptUrl = scriptUrl
|
|
const request = new Promise<SgsMapSDKConstructor>((resolve, reject) => {
|
|
const existingScript = findExistingScript(scriptUrl)
|
|
const script = existingScript || document.createElement('script')
|
|
|
|
const resolveLoadedSdk = () => {
|
|
if (!window.SGSMapSDK) {
|
|
reject(new Error('SGS Map SDK 脚本已加载,但未发现 window.SGSMapSDK'))
|
|
return
|
|
}
|
|
|
|
resolve(window.SGSMapSDK)
|
|
}
|
|
|
|
script.addEventListener('load', resolveLoadedSdk, { once: true })
|
|
script.addEventListener('error', () => {
|
|
reject(new Error(`SGS Map SDK 脚本加载失败: ${scriptUrl}`))
|
|
}, { once: true })
|
|
|
|
if (!existingScript) {
|
|
script.src = scriptUrl
|
|
script.async = true
|
|
document.head.appendChild(script)
|
|
return
|
|
}
|
|
|
|
if (window.SGSMapSDK) {
|
|
resolveLoadedSdk()
|
|
}
|
|
}).finally(() => {
|
|
loadRequest = null
|
|
})
|
|
|
|
loadRequest = request
|
|
return request
|
|
}
|