UNPKG

@aptpod/data-viz-visual-parts-sdk

Version:

Visual Parts SDK for VM2M Data Visualizer

87 lines 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ScriptLoader = void 0; const events_1 = require("events"); class ScriptLoader { constructor() { this.dispose = () => { this.disposeEvents(); this.disposeCachedMem; }; this.load = (url) => { return new Promise((resolve) => { const onResponse = (res) => { if (res.url === url) { this.event.off('reponseLoad', onResponse); resolve(res.status); } }; this.event.on('responseLoad', onResponse); this.event.emit('requestLoad', { url }); }); }; this.disposeEvents = () => { this.event .eventNames() .forEach((name) => this.event.removeAllListeners(name)); }; this.disposeCachedMem = () => { Object.values(this.cachedMem).forEach((mem) => { if (mem.script) { document.head.removeChild(mem.script); } }); this.cachedMem = {}; }; this.onLoadRequest = (payload) => { const { url } = payload; let mem = this.cachedMem[url]; if (mem && mem.status === 'loading') { // noop return; } if (mem && mem.status === 'succeed') { this.event.emit('responseLoad', { url, status: true }); return; } if (mem && mem.status === 'failed') { this.event.emit('responseLoad', { url, status: false }); return; } this.cachedMem[url] = mem = { status: 'loading', script: null, }; loadScript(url) .then((script) => { this.cachedMem[url] = { status: 'succeed', script }; this.event.emit('responseLoad', { url, status: true }); }) .catch(() => { this.cachedMem[url] = { status: 'failed', script: null }; this.event.emit('responseLoad', { url, status: false }); }); }; this.event = new events_1.EventEmitter(); this.cachedMem = {}; // setup events this.event.on('requestLoad', this.onLoadRequest); } } exports.ScriptLoader = ScriptLoader; const loadScript = (url) => { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = url; script.dataset.scriptURL = url; script.onload = () => { resolve(script); }; script.onerror = (error) => { document.head.removeChild(script); reject(error); }; document.head.append(script); }); }; //# sourceMappingURL=script-loader.js.map