UNPKG

1.78 kBJavaScriptView Raw
1!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self,t.Preload=e())}(this,function(){"use strict";function t(t,e){const o=new XMLHttpRequest;o.open("GET",t,!0),o.responseType="blob";const n=this.getItemByUrl(t);n.xhr=o,o.onprogress=(t=>{if(!t.lengthComputable)return!1;n.completion=parseInt(t.loaded/t.total*100);n.downloaded=t.loaded;n.total=t.total;this.updateProgressBar(n)}),o.onload=(t=>{const s=t.target.response.type;const r=t.target.responseURL;n.fileName=r.substring(r.lastIndexOf("/")+1);n.type=s;n.status=o.status;if(404==o.status)n.blobUrl=n.size=null,n.error=!0,this.onerror(n);else{const e=new Blob([t.target.response],{type:s});n.blobUrl=URL.createObjectURL(e),n.size=e.size,n.error=!1}e(n)}),o.send()}function e(t){let e=0,o=this.stepped?100*this.state.length:0,n=0;for(const t of this.state)t.completion&&n++,this.stepped?t.completion&&(e+=t.completion):this._readyForComputation?(e+=t.downloaded,o+=t.total):e=o=0;this._readyForComputation=n==this.state.length;const s=parseInt(e/o*100);isNaN(s)||this.onprogress({progress:s,item:t})}function o(t){for(var e of this.state)if(e.url==t)return e}function n(t){return new Promise((e,o)=>{this.loaded=t.length;for(let o of t)this.state.push({url:o}),this.preloadOne(o,t=>{this.onfetched(t);this.loaded--;0==this.loaded&&(this.oncomplete(this.state),e(this.state))})})}function s(){for(var t of this.state)t.completion<100&&(t.xhr.abort(),t.status=0);return this.oncancel(this.state),this.state}function r(r){return{state:[],loaded:!1,stepped:r&&r.stepped||!0,onprogress:()=>{},oncomplete:()=>{},onfetched:()=>{},onerror:()=>{},oncancel:()=>{},fetch:n,updateProgressBar:e,preloadOne:t,getItemByUrl:o,cancel:s}}return r});