simple-load-script
Version:
Very simple promise based script and JSONP
2 lines (1 loc) • 1.08 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).simpleLoadScript=t()}(this,(function(){"use strict";const e={url:"",attrs:{},inBody:!1,insertInto:null,removeScript:!1};return function t(r){return Array.isArray(r)?Promise.all(r.map(t)):new Promise(((t,o)=>{if(!("object"==typeof r&&r.url||"string"==typeof r))return console.log({config:r}),void o(new Error("Object with url or url string needed"));const n=Object.assign({},e,"string"==typeof r?{url:r}:r),{url:i,attrs:d,inBody:s,insertInto:c,removeScript:l}=n,u=document.createElement("script"),f=c?document.querySelector(c):s?document.body:document.head;if(d&&"object"==typeof d)for(const e of Object.keys(d))u.setAttribute(e,d[e]);null!=f?(u.addEventListener("load",(()=>{l&&f.removeChild(u),t(l?void 0:u)})),u.addEventListener("error",(()=>{l&&f.removeChild(u),o(new Error("Loading script error"))})),u.src=i,f.appendChild(u)):o(new Error("No DOM element to append script"))}))}}));