Created
March 19, 2012 22:45
-
-
Save beatak/2127830 to your computer and use it in GitHub Desktop.
find broken image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($){ | |
if ($.fn.brokenimage) { | |
return false; | |
} | |
var RETRY = 1, | |
MILSEC_INTERVAL = 747; | |
$.fn.brokenimage = function(opt){ | |
var options = { | |
retry: RETRY, | |
interval: MILSEC_INTERVAL, | |
callback: undefined | |
}; | |
var $my = this; | |
var init = function () { | |
$.extend(options, opt || {}); | |
$my.each( | |
function(i, elm) { | |
if (elm.tagName.toLowerCase() === 'img' && isBrokenImage(elm)) { | |
var $elm = $(elm); | |
if ($elm.data('nophoto')) { | |
return false; | |
} | |
// console.log([elm.src, ' IS BROKEN!!! ', options.interval].join('')); | |
$elm.data('retrycount', 0); | |
invokeTimeout(elm); | |
} | |
} | |
); | |
}; | |
var retryImage = function (elm) { | |
var $elm = $(elm); | |
var retrycount = parseInt($elm.data('retrycount'), 10); | |
if (retrycount >= options.retry) { | |
if (typeof options.callback === 'function') { | |
options.callback(elm); | |
} | |
return false; | |
} | |
elm.src = buildRetryUrl(elm.src); | |
$elm.data('retrycount', ++retrycount); | |
invokeTimeout(elm); | |
}; | |
var invokeTimeout = function (elm) { | |
var $elm = $(elm); | |
setTimeout( | |
function () { | |
if (isBrokenImage(elm)) { | |
retryImage(elm); | |
} | |
}, | |
options.interval | |
); | |
}; | |
init(); | |
}; | |
var buildRetryUrl = function (url) { | |
var result; | |
var epoch = ('' + (new Date()).valueOf()).slice(-6); | |
if (url.indexOf('?') > -1) { | |
result = [url, '&__retry=', epoch].join(''); | |
} | |
else { | |
result = [url, '?__retry=', epoch].join(''); | |
} | |
return result; | |
}; | |
var isBrokenImage = function (elm) { | |
var result = false; | |
if (!elm.complete || typeof elm.naturalWidth == "undefined" || elm.naturalWidth == 0) { | |
result = true; | |
} | |
return result; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment