提交室内导览交互与讲解优化
This commit is contained in:
60
src/services/sgs/SgsMapScriptLoader.ts
Normal file
60
src/services/sgs/SgsMapScriptLoader.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user