[Vuejs]-Change image source (twice) when src does not exist

1πŸ‘

I suggest you to use https://imagesloaded.desandro.com/

You can understand if the path exist in this way

$('#container').imagesLoaded()
  .always( function( instance ) {
    console.log('all images loaded');
  })
  .done( function( instance ) {
    console.log('all images successfully loaded');
  })
  .fail( function() {
    console.log('all images loaded, at least one is broken');
  })

In the Fail function you can re-make imagesLoaded() for another path and so on

0πŸ‘

An easy way to implement this would be to make a component out of the object you are using in your v-for loop.

Then you can simply used a computed property to check the src property on your object.

in this case you do:

const image = new Image() 

And then set the src like so:

image.src = <object>.src 

After you have set the src on the Image object you could then check if your specified image has loaded with onload or has failed with onerror.

I do something similarly in my code by check if an image has loaded or not so I can replace the placeholder image with the actual loaded image:

setImagePlaceholder(hotel) {
    this.$set(hotel, 'imgLoaded', false);

    const image = new Image();
    image.src = hotel.thumbUrl;

    image.onload = () => {
        hotel.imgLoaded = true;
    };
}

Don’t know how I could make it any easier for you.

-1πŸ‘

Herre a simple demo, you need to add the recurseve second try.

var img = new Image();

img.onload=function(){
     console.log('loaded!');
 };
 img.onerror = function(){
    console.log("error");
 }
 img.src='something';

Leave a comment