Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Created September 17, 2012 04:22
Show Gist options
  • Save pamelafox/3735530 to your computer and use it in GitHub Desktop.
Save pamelafox/3735530 to your computer and use it in GitHub Desktop.
Load Visible Images
function loadVisibleImages() {
var placeholders = {
'meal': 'img/meal.png',
'avatar': 'img/blankpic.png'
};
$('img').each(function() {
var $img = $(this);
var realUrl = $img.attr('data-src');
if (!realUrl) return;
// If the image is visible and in view, try to load the real image.
// If fails, load the placeholder URL.
var placeholderUrl = $img.attr('data-placeholder') && placeholders[$img.attr('data-placeholder')];
if ($img.attr('src') != realUrl && ED.util.isVisible($img) && ED.util.inView($img, 500)) {
$img.attr('src', realUrl);
$img.on('error', function() {
if (placeholderUrl && $img.attr('src') != placeholderUrl) {
$img.attr('src', placeholderUrl);
}
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment