Search code examples
javascriptjquerycssimagemodernizr

Detect if browser disables images


I need to detect if the browser disables images on the current page. Is this possible with JavaScript (jQuery/Modernizr)?

Problem: The project uses image sprites for icons and displays them like <i class="icon-user"></i>. The app is partially used by mobile users and some of them disable images if they're surfing with edge. As a result some buttons disappear.

The only thing I need is to display something (a gray square, circle…) if images are blocked. Via CSS class on the <html> element or so (class="no-images" e.g.). Writing alternative text between <i>…</i> is unhappily no option.

Thanks for your thoughts! I hope it exists a simple solution.


Solution

  • You can use the following script:

    function noimage()
    {
        if ((document.getElementById('flag').offsetWidth==1 
             && document.getElementById('flag').readyState=='complete')
             ||(document.getElementById('flag').offsetWidth==1
             && document.getElementById('flag').readyState==undefined))
        {
             var objHead = document.getElementsByTagName('head');
             var objCSS = objHead[0].appendChild(document.createElement('link'));
             objCSS.rel = 'stylesheet';
             objCSS.href = 'alt.css';
             objCSS.type = 'text/css';
        }
    }
    

    And you need the following html markup:

    <body onload="noimage();">
    <img id="flag" src="clear.gif" alt="">
    

    Just add it to the body. What this does is check the offsetWidth property to look for a 1x1 pixel image at the top of the browser. If it returns true it means that images are enabled.

    If you need more info go here.