Skip to main content
JavascriptVueVuetify

Validating image existence on the client side with JavaScript, Vue & Vuetify

By June 13, 2023No Comments

Validating an image path on a client-side is slightly tricky. It is easy with

1
<v-img @error
for simple usage but for a more real-world or complex setup, where we want to programmatically check whether the image path is valid or not is slightly tricky. 

1
2
3
<v-img v-if="!showIconFromCommon && !showInitials"
                       :src="getIconPath()" :title="appName" @error="setShowIconFromCommon"
                />

However, with the following function, life is easy. One thing to note though: it throws a browser error, if the image is found missing. I’m yet to look into if the error can be suppressed by wrapping a try/catch block.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// CHECK IF IMAGE EXISTS
        checkIfImageExists (url, callback) {
            const img = new Image()
            img.src = url

            if (img.complete) {
                callback(true)
            } else {
                img.onload = () => {
                    callback(true)
                }

                img.onerror = () => {
                    callback(false)
                }
            }
        },

Usage:

1
2
3
4
5
6
7
                self.checkIfImageExists(self.getIconPath(), (exists) => {
                    if (exists) {
                        self.showIconFromCommon = false
                        self.showInitials = false
                    } else {
}
                })