Specify Default Images for your <img>
tags to be loaded when their images fail to load.
Simply place the script in default-src.js
at the bottom of your page.
if (jQuery) { | |
$('img[default-src]').each(function () { | |
var $elem = $(this); | |
this.onerror = function () { | |
if ($elem.attr('src') != $elem.attr('default-src')) $elem.attr('src', $elem.attr('default-src')); | |
} | |
}); | |
} |
I think just a method would even do. Below is an untested code:
// default-src.js
(function($){
$.defaultSrc = function() {
$('img[default-src]').on('error', function(){
if ($(this).attr('src') !== $(this).attr('default-src'))
$(this).attr('src', $(this).attr('default-src'));
}};
};
})(jQuery);
Usage would be:
<script src="path/to/default-src.js"></script>
<script>
$.defaultSrc();
</script>
Why not turn the thing into a plugin? Makes it neat for usage.