preload-it-extended
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.85 kB
JavaScript
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 r=t.target.response.type;const s=t.target.responseURL;n.fileName=s.substring(s.lastIndexOf("/")+1);n.type=r;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:r});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 r=parseInt(e/o*100);isNaN(r)||this.onprogress({progress:r,item:t})}function getItemByUrl(t){for(var e of this.state)if(e.url==t)return e}function prepareItem(t){return"string"==typeof t?{url:t}:{url:t.url,meta:t.meta}}function getUrlByItem(t){return"string"==typeof t?t:t.url}function fetch(t){return new Promise((e,o)=>{this.loaded=t.length;for(let o of t)this.state.push(prepareItem(o)),this.preloadOne(getUrlByItem(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;