Skip to content

Instantly share code, notes, and snippets.

@tsi
Last active August 29, 2015 13:56
Show Gist options
  • Save tsi/8955462 to your computer and use it in GitHub Desktop.
Save tsi/8955462 to your computer and use it in GitHub Desktop.
This script checks for images load errors and try to load the image from a fallback provided server name.
/**
* This script checks for image load errors.
* It will try to load the image from a fallback provided server name.
*
* Usage:
*
* - Include it:
* <script src="/js/imgProxy.js"></script>
*
* - Call it from your script (or un-comment the call below):
* $(window).load(function() {
* $('img').imgProxy('http://path.to.your.proxy.server');
* });
*
*/
(function($) {
// Modify the path to the proxy server.
$(window).load(function() {
$('img').imgProxy('http://path.to.your.proxy.server');
});
$.fn.extend({
imgProxy: function(proxy) {
// Security - pre-process the string to escape regex special (meta) characters.
function escapeRegex(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
// Helper - String replacement.
function stringReplace(find, replace, str) {
return str.replace(new RegExp(escapeRegex(find), 'g'), replace);
}
// Helper - Return base domain name only. e.g. yahoo.co.in
function getBaseUrl(url) {
try {
var start = url.indexOf('\/\/');
start = start < 0 ? 0 : start + 2;
var end = url.indexOf('\/', start);
if (end < 0) {
end = url.length;
}
return url.substring(start, end);
}
catch (arg) {
return url;
}
}
// Replace broken images.
$(this).each(function() {
var that = this;
if (!that.complete || typeof that.naturalWidth == "undefined" || that.naturalWidth == 0) {
that.src = stringReplace(getBaseUrl(that.src), getBaseUrl(proxy), that.src);
}
});
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment