UNPKG

dynamic-loading-script

Version:
78 lines (77 loc) 2.73 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // index.ts var dynamic_loading_script_exports = {}; __export(dynamic_loading_script_exports, { default: () => dynamic_loading_script_default }); module.exports = __toCommonJS(dynamic_loading_script_exports); function dynamic_loading_script_default(url, option) { return new Promise((resolve, reject) => { const { variableName, timeout, callback, jsonpCallbackName } = option; let timer; let script; if (typeof url === "string") { if (!variableName) { reject(new Error("variableName\u4E0D\u80FD\u4E3A\u7A7A")); return; } if (window[variableName]) { callback && callback(window[variableName]); resolve(window[variableName]); return; } if (jsonpCallbackName) { window[jsonpCallbackName] = () => { resolve(window[variableName]); delete window[jsonpCallbackName]; timer && clearTimeout(timer); callback && callback(window[variableName]); }; } if (timeout !== false) { timer = window.setTimeout(() => { if (!window[variableName]) { script.onload = null; script.onerror = null; document.body.removeChild(script); reject(new Error("\u52A0\u8F7D\u8D85\u65F6")); } }, timeout || 1e4); } script = document.createElement("script"); script.src = url; script.type = "text/javascript"; script.onload = () => { if (jsonpCallbackName) return; timer && clearTimeout(timer); callback && callback(window[variableName]); resolve(window[variableName]); }; script.onerror = () => { timer && clearTimeout(timer); reject(new Error("\u52A0\u8F7D\u5931\u8D25")); }; document.head.appendChild(script); } else { throw new Error("url\u7C7B\u578B\u4E0D\u6B63\u786E"); } }); } //# sourceMappingURL=index.js.map