@maz-ui/utils
Version:
Utils of maz-ui for JavaScript/TypeScript users
44 lines (43 loc) • 1.64 kB
JavaScript
class s {
src;
script;
once;
async;
defer;
identifier;
constructor({ src: e, identifier: t, once: o = !0, async: r = !0, defer: i = !0 }) {
if (typeof globalThis.window > "u")
throw new TypeError("[ScriptLoader]: Is supported only on browser side");
if (!e)
throw new Error('[ScriptLoader]: You should provide the attribut "src"');
if (!t)
throw new Error('[ScriptLoader]: You should provide the attribut "identifier"');
this.src = e, this.identifier = t, this.once = o, this.async = r, this.defer = i;
}
removeTag(e) {
typeof e == "string" ? document.head.querySelector(`[data-identifier="${e}"]`)?.remove() : e.remove();
}
load() {
const e = globalThis, t = document.head.querySelectorAll(`[data-identifier="${this.identifier}"]`);
if (this.once && e[this.identifier] && t.length > 0)
return this.script = e[this.identifier], Promise.resolve(this.script);
if (!this.once && t.length > 0)
for (const o of t)
this.removeTag(o);
return this.injectScript();
}
injectScript() {
const e = globalThis;
return new Promise((t, o) => {
try {
const r = document.createElement("script");
r.src = this.src, r.async = this.async, r.defer = this.defer, r.dataset.identifier = this.identifier, r.addEventListener("error", (i) => o(new Error(`[ScriptLoader](injectScript) ${i.message}`))), r.addEventListener("load", (i) => (this.script = i, e[this.identifier] = i, t(i))), document.head.append(r);
} catch (r) {
throw new Error(`[ScriptLoader](init) ${r}`);
}
});
}
}
export {
s as ScriptLoader
};