const scriptCache = new Map>(); /** * 确保指定 URL 的外部脚本在页面中只被加载一次。 * 返回 Promise,若已在加载中或已完成则复用同一个 Promise。 */ export function loadScriptOnce(url: string): Promise { const normalizedUrl = url.trim(); if (!normalizedUrl) { return Promise.reject(new Error("Empty script URL provided")); } const cached = scriptCache.get(normalizedUrl); if (cached) { return cached; } // 检查 DOM 中是否已有对应脚本标签(防御外部已插入场景) const existing = document.querySelector( `script[src="${normalizedUrl}"]`, ); if (existing) { const existingPromise = Promise.resolve(); scriptCache.set(normalizedUrl, existingPromise); return existingPromise; } const promise = new Promise((resolve, reject) => { const script = document.createElement("script"); script.src = normalizedUrl; script.async = true; script.onload = () => { resolve(); }; script.onerror = () => { // 加载失败时从缓存移除,允许后续重试 scriptCache.delete(normalizedUrl); script.remove(); reject(new Error(`Failed to load external script: ${normalizedUrl}`)); }; document.head.appendChild(script); }); scriptCache.set(normalizedUrl, promise); return promise; }