Prosto Trader
Prosto Trader

Reputation: 3527

Do not show broken images via Onload property

I have a site with lots of images. Some of them are missing on the server - deleted by the owner.

If image is not loaded (broken) I want to show placeholder - standard image, that indicates that image is missing.

I dont want to rewrite all templates so I cant add onError property to every image tag, so I cant use this solution: jQuery/JavaScript to replace broken images

Is it possible to write global function that will check all images and replace broken on load?

Upvotes: 5

Views: 569

Answers (2)

mikakun
mikakun

Reputation: 2265

for the 65% of website that run on apache (http://w3techs.com/technologies/details/ws-apache/all/all) :

missing image is a server issue that you can fix on the server with a .htaccess in your image folder if you can upload a .htaccess in your image folder

ErrorDocument 404 /PATH/TO/IMAGE/FOLDER/placeholder.png 

client will be 404 free + js payload will be less = your page will load faster

or from root .htaccess if you can upload/edit .htaccess in your root folder, you can :

  <FilesMatch ".(jpg|png|gif)$">
    ErrorDocument 404 /PATH/TO/IMAGE/FOLDER/placeholder.png
  </FilesMatch>

(credit to https://stackoverflow.com/a/10803705/1061871 for that second solution)

Upvotes: 2

antyrat
antyrat

Reputation: 27765

Yes, as you have jQuery in your tags you can use jQuery for that for example.

Bind onerror handler to all <img> nodes:

$( 'img' ).on( 'error', function() {
    $( this ).attr( 'src', 'http://path.to.your/image.jpg' );
});

In plain JS this can be done like this:

var images = document.getElementsByTagName( 'img' )
  , i, len;

for( var i = 0, len = images.length; i < len; i++ ) {
    (function( i ) {
        images[ i ].onerror = function() {
            images[ i ].onerror = null;
            images[ i ].src = 'http://path.to.your/image.jpg';
        };
    })( i );
}

Upvotes: 7

Related Questions