UNPKG

resource-manager-js

Version:

Loads and caches all resources needed for a web app including css, templates, and scripts

1 lines 2.75 kB
(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):global["ResourceManager "]=factory()})(this,function(){"use strict";let ensurePathArray=function(paths){if(!paths){paths=[]}else if(typeof paths==="string"){paths=[paths]}return paths};class ResourceManager{constructor(){this._head=document.getElementsByTagName("head")[0];this._cssPaths={};this._scriptMaps={};this._dataPromises={}}async loadScript(paths){let script,map,loadPromises=[];paths=ensurePathArray(paths);paths.forEach(path=>{map=this._scriptMaps[path]=this._scriptMaps[path]||{};if(!map.promise){map.path=path;map.promise=new Promise(resolve=>{script=this.createScriptElement();script.setAttribute("type","text/javascript");script.src=path;script.addEventListener("load",resolve);this._head.appendChild(script)})}loadPromises.push(map.promise)});return Promise.all(loadPromises)}async unloadScript(paths){let file;return new Promise(resolve=>{paths=ensurePathArray(paths);paths.forEach(path=>{file=this._head.querySelectorAll('script[src="'+path+'"]')[0];if(file){this._head.removeChild(file);delete this._scriptMaps[path]}});resolve()})}createScriptElement(){return document.createElement("script")}async fetchData(url,reqOptions={}){let cacheId=url+JSON.stringify(reqOptions);reqOptions.cache=reqOptions.cache===undefined?true:reqOptions.cache;if(!url){return Promise.resolve()}if(!this._dataPromises[cacheId]||!reqOptions.cache){try{this._dataPromises[cacheId]=await fetch(url,reqOptions)}catch(e){this._dataPromises[cacheId]=null;throw e}}return this._dataPromises[cacheId]}async loadCss(paths){return new Promise(resolve=>{paths=ensurePathArray(paths);paths.forEach(path=>{if(!this._cssPaths[path]){let el=document.createElement("link");el.setAttribute("rel","stylesheet");el.setAttribute("href",path);this._head.appendChild(el);this._cssPaths[path]=el}});resolve()})}async unloadCss(paths){let el;return new Promise(resolve=>{paths=ensurePathArray(paths);paths.forEach(path=>{el=this._cssPaths[path];if(el){this._head.removeChild(el);this._cssPaths[path]=null}});resolve()})}async loadTemplate(path,el){if(!path){return Promise.resolve()}const contents=await this.fetchTemplate(path);if(el){el.innerHTML=contents;return el}return contents}async fetchTemplate(templatePath){const resp=await fetch(templatePath);return await resp.text()}async flush(){await this.unloadCss(Object.getOwnPropertyNames(this._cssPaths));this._cssPaths={};for(let s in this._scriptMaps){if(this._scriptMaps.hasOwnProperty(s)){let map=this._scriptMaps[s];await this.unloadScript(map.path)}}this._scriptMaps={};this._dataPromises={}}}const resourceManager=new ResourceManager;return resourceManager});