UNPKG

load-scripts

Version:

Dynamic scripts loading for modern browsers.

38 lines (34 loc) 1.39 kB
/*! load-scripts v2.0.0 | (c) 2018-present Chen Fengyuan | MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.loadScripts = factory()); }(this, (function () { 'use strict'; function loadScripts(...urls) { return Promise.all(urls.map((url) => new Promise((resolve, reject) => { const parent = document.head || document.body || document.documentElement; // Avoid loading script repeatedly if (parent.querySelector(`script[src*="${url}"]`)) { resolve(url); return; } const script = document.createElement('script'); const loadend = () => { script.onerror = null; script.onload = null; }; script.onerror = () => { loadend(); reject(new Error(`Failed to load script: ${url}`)); }; script.onload = () => { loadend(); resolve(url); }; script.async = true; script.src = url; parent.appendChild(script); }))); } return loadScripts; })));