So what to do? Using progressive enhancement you wouldn't want to implement something unless you know it's supported, you can use JavaScript to test if images are enabled and then add a class name to the html tag is one way to go.
Browsers seem to fall into two camps when images are turned off. Ones that don't load images at all and ones that load all img tags with an empty image. So you need to create two tests, first attach an onload function to an image you know exists, this will not fine on browsers that don't load images at all.
e.g...
var existentimg = new Image;
existentimg.onload = function(){
// if this didn't fine, images aren't enabled
}
existentimg.src = "know_to_exist.png";
As the above will fire on browsers that load images when images are disabled you need to do the same test again but this time attach the onload to an image you know does not exist.
e.g...
var nonexistentimg = new Image;
nonexistentimg.onload = function(){
// if this fires, images are disabled
}
nonexistentimg.src = "/nonexistent.gif";
I've put an example function at the bottom of this page that combines the two functions.
What to do with the info when you have it? Once you know if the user-agent has images enabled you can add a class name (e.g. "img") to the HTML tag, this will provide a way of using the information in your CSS.
e.g...
/* these styles will only be implemented if images are enabled */
html.img h1 {background-image:url(H1.png);width:XXXpx;height:XXpx;}
html.img h1 span {position:absolute;left:-9999px;}
Anonymous JavaScript function example, run this on DOM ready
(function(existingimageurl){
var existentimg = new Image;
existentimg.onload = function(){
document.getElementsByTagName('html')[0].className+= " img";
var nonexistentimg = new Image;
nonexistentimg.onload = function(){
document.getElementsByTagName('html')[0].className = document.getElementsByTagName('html')[0].className.replace(/\bimg\b/,"");
}
nonexistentimg.src="/nonexistentimg.png";
}
existentimg.src = existingimageurl || (document.images.length?document.images[0].src:'http://www.google.co.uk/images/nav_logo.png');
})();
If your using jQuery (or something similar) and you know there is at least one image on your page...
$(document).ready(function(){
(function(){
var existentimg = new Image;
existentimg.onload = function(){
$('html').addClass('img');
var nonexistentimg = new Image;
nonexistentimg.onload = function(){
$('html').removeClass('img');
}
nonexistentimg.src="/nonexistent.gif";
}
existentimg.src = document.images[0].src;
})();
})
No comments:
Post a Comment