Created
October 19, 2016 10:11
-
-
Save shanna/579c4301ee879103c93f8eee51370fdf to your computer and use it in GitHub Desktop.
Broken image JS.
This file contains 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
// MIT https://github.com/alexrabarts/jquery-brokenimage minus the jquery. | |
function BrokenImage(selector, options) { | |
'use strict'; | |
options = options || {}; | |
var defaults = { | |
timeout: 2500 | |
}; | |
for (var key in defaults) { | |
if (!options.hasOwnProperty(key)) { | |
options[key] = defaults[key]; | |
} | |
} | |
var elements = document.querySelectorAll(selector); | |
Array.prototype.forEach.call(elements, function(image){ | |
if (!image instanceof HTMLImageElement) | |
return; | |
image.addEventListener('error', placeholder); | |
setTimeout(function () { | |
var test = new Image(); | |
test.src = image.src; | |
if (test.height === 0) { | |
placeholder(); | |
} | |
}, options.timeout); | |
function placeholder() { | |
if (options.replacement) { | |
image.src = options.replacement; | |
} | |
else { | |
image.style.visibility = 'hidden'; | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment