Using JavaScript to check if images are enabled

Sometimes it’s useful to know if images are enabled in the user’s browser, so that you can adjust your CSS and/or JavaScript to make sure that important content is not hidden and that the page is still usable even if images aren’t loaded.

Steve Faulkner describes one example of such a scenario in Detecting if images are disabled in browsers—using an image to convey information that is also available in text that is positioned off-screen. In a CSS on + images off scenario, sighted users won’t get any information.

It’s often possible to write your markup and CSS in a way that avoids this problem, but it isn’t always practical. Hence knowing whether images will be displayed or not is helpful.

In the article I linked to, Steve provides a script that will check if images are disabled by checking the width of an image on the page. I thought I’d take a look at a different approach—checking if images are enabled instead.

It’s a simple script:

(function() {
	var image = new Image();
	image.onload = function() {
		if (image.width > 0) {
			document.documentElement.className += (document.documentElement.className != '') ? ' images-on' : 'images-on';
		}
	};
	image.src = 'px.png';
}());

It requires an image that exists—in this case a 1x1 pixel, transparent image. (Remember when we loaded images like that a zillion times to size our table-based layouts? No? Lucky you.)

The script creates a new image object, assigns an onload event to it, and finally sets the image as the source. If the onload event is triggered and the image’s width is larger than 0, the class name “images-on” is added to the body element. Try it out on the demo page and toggle image loading on and off in your browser.

After running the script you can write rules like this:

.your-class-name {
	/* Declarations that require images */
}
body:not(.images-on) .your-class-name {
	/* Fallback declarations */
}

If you want better backwards compatibility (the negation pseudo-class, :not, is IE9+) you’ll need to do this:

.your-class-name {
	/* Basic declarations */
}
body.images-on .your-class-name {
	/* Declarations for progressive enhancement */
}

I’m aware of these issues:

The best approach is to write CSS that doesn’t fail catastrophically if images aren’t displayed, but when you can’t do that, this is a useful backup.

Posted on November 1, 2012 in CSS, JavaScript, Accessibility