Last active
August 29, 2015 14:27
-
-
Save AprilArcus/90cfe2294b0d259f2751 to your computer and use it in GitHub Desktop.
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
<!-- polyfills --> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.34/bluebird.min.js"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/0.9.0/fetch.min.js"> | |
<script> | |
var imageCache = {}; | |
function preload(name) { | |
var url = "images/" + name + ".jpg"; | |
return fetch(url) // returns a promise... | |
.then(function(response) { // ...which resolves with the HTTP response | |
return response.blob(); // returns another promise... | |
}) | |
.then(function(blob) { // ...which resolves with a Binary Large OBject | |
// build a DOM node with the resolved BLOB... | |
var img = document.createElement("img"); | |
img.src = URL.createObjectURL(blob); | |
// ...and write it into the cache by side-effect | |
imageCache[name] = img; | |
}); | |
} | |
var imageNames = ["capsule", "transit", "city-haze", "city", "garage", "restroom", "storage", "jungle", "pool"]; | |
var imagePromises = imageNames.map(preload); | |
Promise.all(imagePromises) | |
.then(function() { | |
// This callback fires once all images have loaded and the cache is ready. | |
// inject the cache into your app as a parameter, so that it doesn't have to | |
// concern itself with where images come from. | |
main({images: imageCache}); | |
}) | |
.catch(function(error) { | |
console.log(error); | |
}); | |
function main(options) { | |
var imageCache = options.images; | |
// do whatever work you need to do with the image cache here | |
document.body.appendChild(imageCache.capsule); | |
// if you want, manually release the image from memory when you are done with it | |
document.body.removeChild(imageCache.capsule); | |
URL.revokeObjectURL(imageCache.capsule.src); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment