Created
April 18, 2016 17:09
-
-
Save stevenschobert/c007adac9139faa7a08fc45e4aae804d to your computer and use it in GitHub Desktop.
Image preloader
This file contains hidden or 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
/** | |
* Loads images for a section of dom tiles. Loads the image in the | |
* background and then removes loading indicators once loaded. | |
* | |
* Takes an array of dom nodes, a single dom node, or a css selector. | |
*/ | |
function loadTileImages(imageEls) { | |
if (typeof imageEls !== 'string' && !Array.isArray(imageEls)) { | |
imageEls = [imageEls]; | |
} | |
if (typeof imageEls === 'string') { | |
if (imageEls.indexOf('tile-image') < 0) { | |
imageEls = imageEls + ' .tile-image'; | |
} | |
imageEls = document.querySelectorAll(imageEls); | |
} | |
imageEls = [].slice.call(imageEls); | |
imageEls = imageEls.filter(function checkForTileImageClass(el) { | |
return el.className && el.className.indexOf('tile-loading') >= 0; | |
}); | |
imageEls.forEach(function preloadImageData(el) { | |
var imageUrl = el.getAttribute('data-image-url'); | |
var imageLink = el.getAttribute('data-image-link'); | |
if (imageUrl) { | |
preloadImage(imageUrl, function swapImage(image) { | |
var elToAppend; | |
if (imageLink) { | |
elToAppend = document.createElement('a'); | |
elToAppend.setAttribute('href', imageLink); | |
elToAppend.appendChild(image); | |
} else { | |
elToAppend = image; | |
} | |
el.appendChild(elToAppend); | |
setTimeout(function removeLoadingIndicator() { | |
el.setAttribute('class', el.getAttribute('class').replace(/(.*)tile-loading(.*)/, '$1$2')); | |
}, 250); | |
}); | |
} | |
}); | |
} | |
function preloadImage(url, callback) { | |
var img = document.createElement('img'); | |
img.onload = function(event) { | |
callback(img, event); | |
}; | |
img.src = url; | |
return img; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment