Avoiding URL images on 404 errors in frontend applications

My goal is to dynamically implement images (from image_url_1.jpg to image_url_5.jpg) based on a specific URL. While everything works fine, I encounter an issue when a particular image, like "image_url_4.jpg," is not available and results in a 404 Error causing the broken image symbol to be displayed consistently.

Is there a way for me to check within my v-for loop if an image returns a 404 error or cannot be displayed, and then skip it using a conditional statement like v-if?

I have attempted to use require(url), but unfortunately, it has not worked as expected.

Example Code

<template>
  <div v-for="(n, index) in 5" :key="index">
    <img :src="'image_url_' + n + '.jpg'" />
  </div>
</template>

Visualization with an image:

https://i.sstatic.net/p8MKspfg.png

Answer №1

One of the events that an HTML element can have is the error event: (MDN Web Docs)

The error event occurs when a resource fails to load or cannot be used. This could happen if a script encounters an error during execution or if an image cannot be found or is invalid.

Implementing this event is straightforward: (demo)

<script setup lang="ts">
import { ref } from 'vue';

const num = 4;
const show = ref(new Array(num + 1).fill(true)); // using "of" in v-for, index starts from 1

function handleError(index) {
  show.value[index] = false;
}
</script>

<template>
  <template v-for="index of num">
    <div v-if="show[index]">
      <img :src="`/images/${index}.png`" @error="handleError(index)" />
    </div>
  </template>
</template>

If you are using Vite and your images are located within the project (and can be imported as URLs), there is another method with improved performance: (demo)

<script setup lang="ts">
function getImages() {
  // All images are under `./images` and have the extension `.png`
  const original = import.meta.glob('./images/*.png', {
    eager: true,
    import: 'default',
  });
  
  const transformed = Object.entries(original)
    .map(([key, value]) => [
      key.replace('./images/', '').replace('.png', ''),
      value,
    ]);

  return Object.fromEntries(transformed); 
}

const images = getImages();
</script>

<template>
  <div v-for="(path, index) in images" :key="index">
    <img :src="path" />
  </div>

The first method involves attempting to load each image dynamically and excluding any items that fail to load.

The second method entails importing the URLs of all images at compile time and displaying them based on their actual URLs. This approach allows determining the images during build time, resulting in better performance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

Implementing VueJS3 - How to activate a function upon receiving an event from a sibling component

I need to execute a function that retrieves data from an http-server in one component, once a button in another component is clicked. SignUpForm.vue contains a button that calls the customSubmit() method customSubmit(){ //POST to API const user = { ...

Exploring the dynamic loading of JavaScript functions with Ajax in Dojo while passing arguments

Currently, I am working on implementing a require/load function that handles the retrieval and execution of remote JavaScript code. The function is functioning well, but I have been using a workaround to pass arguments by setting global variables. However, ...

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...

How can I use VB codebehind in ASP to display a dialog box to the user asking for a yes or no response?

I am faced with a scenario where a user has chosen a product, the system has retrieved the product record, and the backorder flag has been set. I need to inquire if the user still wants to proceed with including the product in the order. However, I am stru ...

FlexSlider in WordPress is failing to display captions

Before pointing out any similar questions, please note that the answer from those sources does not apply to my specific code. I am trying to achieve this through a function as outlined here But I am struggling to figure out how to add captions only if th ...

Leveraging the import statement within lib.d.ts to enhance Intellisense functionality in Visual Studio Code

Looking to streamline my JavaScript project by utilizing custom global variables and harnessing the power of VSCode intellisense for auto completion. Here's what I'm aiming for: See example of auto completion for 'lol' After some sear ...

Ember.js - The Veggie Power-Up: [object Object] encountered an error with:

I've recently started using ember and have set up a sandbox to experiment with it. An interesting issue arises when I run the ember s command - an error pops up, but here's the strange part: the error only occurs when I have Sublime Text open (!? ...

Stop Carousel when hovering over individual items (Owl Beta 2)

After creating a unique navigation that is separate from the carousel, I encountered some issues with the autoplay feature. Below is the HTML markup: <div class="carousel"> <div class=""> <img src="assets/img/carousel1.jpg" /&g ...

Send properties to the makeStyles function and apply them in the CSS shorthand property of Material UI

When working with a button component, I pass props to customize its appearance: const StoreButton = ({ storeColor }) => { const borderBottom = `solid 3px ${storeColor}`; const classes = useStyles({ borderBottom }); return ( <Button varian ...

React filtering displaying array elements that appear single time

I've been working on this React code to filter and search items based on user input. The issue I'm facing is that when I delete the text input and try again, the filtered items disappear and don't show up unless I reload the page. I'm c ...

Creating a Javascript object from a JSON string

Looking for a way to convert a JSON string into a JavaScript object? You can make use of the following code snippet obtained from the server: JSON String: ["{"title":"Admin Dhaka","href":"#0","dataAttrs":[],"data":["{\"title\":\"BNS HAJI M ...

Fade In Effect in Angular 2 Using SwitchCase

Hi everyone, I'm facing an issue with making my switch cases fade in after one is called. Here's what I have so far. When the correct switch case is entered in the input field, I want the current one to fade out and the new one to fade in. How ...

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

Using JavaScript to we can transfer the function result to an HTML input field

Is there a way to display the result of a JavaScript function in an HTML input field? Here is an example form: https://i.sstatic.net/HHHl2.png When I click "Run - Script," the following simple script is executed: <button type="submit" class="btn btn ...

How to give focus to a div in IE 8 after pressing the tab key, no jQuery required

We are facing a challenge with our datagrid where we have implemented navigation using the tab key. In IE 7 & 8, pressing the tab key shifts the focus away from the grid to the next element on the page. While in other browsers, we were able to prevent thi ...

Execute a JavaScript function when a form is submitted

Seeking to reacquaint myself with Javascript, encountering difficulties with this fundamental issue. https://jsfiddle.net/gfitzpatrick2/aw27toyv/3/ var name = document.getElementById("name"); function validate() { alert("Your name is " +name); } < ...

When utilizing the @Prop decorator in TypeScript, the compiler throws an error prompting the need to initialize the prop

Currently, I am utilizing Vue in combination with TypeScript along with the 'vue-property-decorator' package. When attempting to utilize a prop as shown below: @Prop({ default: '' }) private type: string An error is triggered by the ...

The switch statement is not yielding any results

I am currently working on a test that involves processing a string through a switch statement. However, I am facing an issue where the integer value set in the case of the switch statement is not being passed correctly. As a result, the subsequent if state ...

Retrieving chosen items from NextUI-Table

I am completely new to JavaScript and NextUI. My usual work involves C# and DotNET. I have a requirement to create a table with selectable items, and when a button is clicked, all the selected items should be passed to a function on the server that accepts ...