Skip to content

Instantly share code, notes, and snippets.

@cyberwombat
Created May 25, 2016 19:36
Show Gist options
  • Save cyberwombat/b4f7f4d409eaec810bb0ce3279239acc to your computer and use it in GitHub Desktop.
Save cyberwombat/b4f7f4d409eaec810bb0ce3279239acc to your computer and use it in GitHub Desktop.
Angular delayed image load directive
/*
* Angular directive to insert an image from a source that may require a few seconds
* to become available such as a thumb created by server to AWS S3.
* This directive checks if the image yields an error, if so it will loop a HEAD request
* every intevrval (default to 500ms, 5 times), If that fails then it will jus use the
* fallback image
* This directive will only peform an HTTP request when the initial loading image fails
*/
angular.module('app').directive('preview', function(stickerService, $http, $interval) {
return {
restrict: 'A',
replace: true,
template: '<img class="preview" style="display:none" ng-src="{{ url }}"/>',
scope: {
preview: '@',
format: '@'
},
link: function(scope, elem, attr) {
var error = false
// Assign our desired image
scope.url = attr.preview
// On load show the img tag - this prevents broken image links
elem.bind('load', function() {
angular.element(this).css("display", 'block');
})
// If error (such as a 403 from an S3 thumb not yet being available then loop and check
elem.bind('error', function() {
// We already went through this, give up
if (error) {
elem.attr("src", '/fallback_image.png')
return
}
error = true
// HEAD check for image, if ready then insert
var stop = $interval(function() {
return $http.head(attr.preview).then(function(res) {
if (res.status === 200) {
elem.attr("src", attr.preview);
$interval.cancel(stop)
}
return false
})
}, 500, 5)
});
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment