Skip to content

Instantly share code, notes, and snippets.

@danwoods
Created August 4, 2011 20:43
Show Gist options
  • Save danwoods/1126213 to your computer and use it in GitHub Desktop.
Save danwoods/1126213 to your computer and use it in GitHub Desktop.
jQuery plugin to catch image load errors and re-direct src urls

jQuery plugin to catch image load errors and re-direct src urls. Allows for multiple fallback options.

Author: Dan Woodson

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"0>
<title>srcFailback example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="jquery.srcFailback.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
$('document').ready(function(){
$('img').srcFailback({
sources: [
{prepend: 'http://fc04.deviantart.net/fs21/i/2008/146/4/e/',
append: '.jpg'
}
]
});
});
</script>
</head>
<body>
<div id="content">
<img id="img_0" src="http://i.imgur.com/YQ9sK.jpg" />
<img id="img_1" src="http://imgur.com/gallery/Jungle_2_0_Wallpaper_by_moiret" />
</div>
</body>
</html>
/*
* jQuery srcFailback plugin
* Description: Alters an elements src attribute on error event
* Author: Dan Woodson
*/
(function($){
$.fn.srcFailback = function(options) {
// Set default options
var defaults = {
sources: [
{ prepend: "testPre/",
append: "/testApp"
}
]
};
options = $.extend(defaults, options);
// Setup regular expression to grab the end of the url and our class tags
var urlRe = new RegExp("([a-zA-Z0-9-_])+$");
var classRe = new RegExp("src_load_error_");
// Operate on objects
return this.each(function() {
// Get reference to current object
obj = $(this);
// Watch for errors loading
obj.error(function() {
// Make sure we haven't already tried all the sources
var new_length = options.sources.length-1;
if(!obj.hasClass('src_load_error_'+new_length)){
// local vars
var prevAttempt = -1;
// See if we've tried any sources previously
var prevAttemptArr = (obj.attr('class') !== undefined?obj.attr('class').match(classRe):[false]);
if (prevAttemptArr !== null && prevAttemptArr[0]) {
prevAttemptArr = prevAttemptArr[0].split('_');
prevAttempt = parseInt(prevAttemptArr[1], 10);
}
// Set current source index
curSourceIndex = prevAttempt + 1;
// Get desired section of url
var matchArr = obj.attr('src').match(urlRe);
var key = matchArr[0];
// change the src attribute of the image (if no append value given, add empty string)
obj.attr("src", options.sources[curSourceIndex].prepend +
key +
(options.sources[curSourceIndex].append?options.sources[curSourceIndex].append:"")
);
// Add/Update classes (this prevents looping, and allows us to try multiple sources
obj.addClass('src_load_error_'+curSourceIndex);
}
// Default return value
return true;
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment