Last active
May 17, 2016 08:04
-
-
Save marlocorridor/55151669b3395d6ce10c5e22171eb22d to your computer and use it in GitHub Desktop.
Loads the assets to be cached by the browser.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// depends on jQuery | |
var PreloaderClass = function (urls) { | |
// holds the URLs passed | |
this.urls = urls; | |
// base loading | |
this.loadUrl = function ( url ) { | |
var supported, deferredLoading, xhr; | |
deferredLoading = jQuery.Deferred(); | |
supported = typeof new XMLHttpRequest().responseType === 'string'; | |
if (supported) { | |
xhr = new XMLHttpRequest(); | |
xhr.open('GET', url, true); | |
xhr.responseType = 'arraybuffer'; | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState === 4) { | |
if (xhr.status === 200) { | |
deferredLoading.resolve( xhr ); | |
} else { | |
deferredLoading.reject( xhr ); | |
} | |
} | |
}; | |
xhr.onprogress = function (evt) { | |
if(evt.lengthComputable) { | |
deferredLoading.notify(evt.loaded, evt.total); | |
} | |
}; | |
xhr.send(null); | |
} | |
return deferredLoading; | |
}; | |
// action method | |
this.preload = function () { | |
var self = this; | |
var deferredLoads = []; | |
this.urls.forEach(function (url) { | |
var getDeferredLoad = self.loadUrl( url ); | |
deferredLoads.push( | |
getDeferredLoad | |
); | |
}) | |
return $.when.apply($, deferredLoads); | |
} | |
}; | |
//preloader usage | |
(function () { | |
var url_set = [ | |
//enter URLs here | |
]; | |
// creates instance | |
window.Preloader = new PreloaderClass( url_set ); | |
// execute preloading | |
Preloader.preload(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment