mirror of
https://github.com/zoriya/v10.git
synced 2026-08-16 02:45:09 +00:00
33 lines
1000 B
JavaScript
33 lines
1000 B
JavaScript
//#region src/dom/script.ts
|
|
const cache = /* @__PURE__ */ new Map();
|
|
function hasScript(src) {
|
|
for (const script of document.scripts) if (script.getAttribute("src") === src) return true;
|
|
return false;
|
|
}
|
|
/**
|
|
* Load a script once. Concurrent and repeat calls for the same `src` share a
|
|
* single promise; failed loads are evicted (and the tag removed) so they can
|
|
* be retried.
|
|
*/
|
|
function loadScript(src) {
|
|
let promise = cache.get(src);
|
|
if (promise) return promise;
|
|
if (hasScript(src)) return Promise.resolve();
|
|
promise = new Promise((resolve, reject) => {
|
|
const script = document.createElement("script");
|
|
script.src = src;
|
|
script.onload = () => resolve();
|
|
script.onerror = () => {
|
|
script.remove();
|
|
reject(/* @__PURE__ */ new Error(`Failed to load script: ${src}`));
|
|
};
|
|
document.head.appendChild(script);
|
|
});
|
|
cache.set(src, promise);
|
|
promise.catch(() => cache.delete(src));
|
|
return promise;
|
|
}
|
|
//#endregion
|
|
export { hasScript, loadScript };
|
|
|
|
//# sourceMappingURL=script.js.map
|