Because of things outside of our control as developers, images don’t always load and the design suffers. This occurs because of a connectivity issues, or when an image path is incorrect or points to a resource that is no longer available.
In the interest of graceful failure, I include a default image as a backup for images that don’t load.
components/default-img.js
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'img',
attributeBindings: ['src'],
didInsertElement: function(){
var _this = this;
// With jQuery
this.$().on('load', function(evt){
return _this.imageLoaded(evt);
}).on('error', function(evt){
return _this.errorLoading(evt);
});
// Without jQuery / for Mobile
/*
var domRef = document.getElementById(this.get('elementId'));
domRef.addEventListener('load', function (evt) {
return _this.imageLoaded(evt);
}, false);
domRef.addEventListener("error", function (evt) {
return _this.errorLoading(evt);
}, false);
*/
},
willDestroyElement: function(){
this.$().off('load', 'error');
},
imageLoaded: function(event){
console.log("Image Loaded");
},
errorLoading: function(event){
this.set('src', this.get('defaultImg'));
}
});
Use:
Controller:
// path to the Expected image var img = data.imgPath; // path to Default / backup image // change this to match design requirements or default image path. var defaultImg = 'http://placehold.it/190x200';
View:
{{default-img src=img defaultImg=defaultImg}}