Skip to content

Instantly share code, notes, and snippets.

@zela
Created March 18, 2011 12:56
Show Gist options
  • Save zela/876022 to your computer and use it in GitHub Desktop.
Save zela/876022 to your computer and use it in GitHub Desktop.
detect if images are allowed in browser
/**
Without waiting in browsers Opera and Webkit:
if pics are allowed
'img.complete' puts on 'true' only after event
'onload', 'onerror' or 'onabort'
if pics are not allowed
instantly 'img.complete' becomes 'true', and 'onload' doesn't occurs
у IE:
if pics are allowed
property 'readyState' [*] changes two times
and trows event 'onreadyState'
if pics are not allowed
property 'readyState' has value 'uninitialized'
Firefox:
if pics are allowed
instantly 'img.complete' becomes 'true', then throws event 'onload'
if pics are not allowed
also instantly 'img.complete' becomes 'true',
after that throws 'onerror'
Таймаут приходится выдерживать, во-первых, для того, чтобы Firefox успел
сообразить, какое событие ему выбрасывать, во-вторых, для того, чтобы IE
успели проинициализировать свойство readyState.
[*] In IE all tag objects with loadable data have property 'readyState'.
It included in HTML5 specification. (Therefore, will work in future
browsers, but not fact, that in the same way as in IE.)
**/
(function() {
function init(){
var img = new Image();
var imgAllowed = false; // variable for detect if event occured
img.src = "http://www.software-dungeon.co.uk/icons/109012_bug.gif";
// wittingly downloadable pic (for preventing onerror event),
// better from own server
img.onload = function() {
imgAllowed = true;
// event occured,
//therefore, pics are allowed (works in all browsers)
alert("Images allowed.");
};
function checkLoading() {
//pic completed, but event hasn't occur (W3C), or it's status
// 'uninitialized' (IE), therefore, pics aren't allowed
if((img.complete && (imgAllowed === false)) ||
img.readyState === 'uninitialized') {
alert ("Images aren't allowed.");
}
}
// check with timeout (weak place in code)
window.setTimeout(checkLoading,200);
document.body.appendChild(img); // for beauty. Opera calls event
// onload for this instruction, even pics are disabled.
}
if (window.addEventListener) {
window.addEventListener("load", init, false);
} else if (window.attachEvent) {
window.attachEvent("onload", init);
} else {
window.onload = init;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment