UNPKG

preload-it

Version:

A tiny 1kb JavaScript library for preloading assets on the browser via XHR2. It provides the ability to load assets of different file types and composite progress events.

2 lines (1 loc) 1.69 kB
function preloadOne(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 updateProgressBar(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 getItemByUrl(t){for(var e of this.state)if(e.url==t)return e}function fetch(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 cancel(){for(var t of this.state)t.completion<100&&(t.xhr.abort(),t.status=0);return this.oncancel(this.state),this.state}function Preload(t){return{state:[],loaded:!1,stepped:t&&t.stepped||!0,onprogress:()=>{},oncomplete:()=>{},onfetched:()=>{},onerror:()=>{},oncancel:()=>{},fetch:fetch,updateProgressBar:updateProgressBar,preloadOne:preloadOne,getItemByUrl:getItemByUrl,cancel:cancel}}export default Preload;