I just started using Vue in the front-end of my website . In one of my Vue-components I want an image with a certain path:
<img src="path/example/with/vue/var">
Now, this is what I want to do:
- Check if the file in "path/example/with/vue/var" exists
- If not: Change the src to "another/path/with/vue/var"
- Check if "another/path/with/vue/var" exist
- If not: Change the src to "default/path"
I already tried to use onerror
with a function inside of it. But the problem is I'm loading 100+ objects with a couple of images for each object. If I just check if the file exists the normal way(through Ajax or with an XMLHttpRequest), the performance is completely gone. All objects are loaded through a JSON file.
I hope you guys understand the question.
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
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.
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';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.