Detecting Image Loading with Javascript

My website is filled with numerous images categorized into 5 different groups, causing it to load slowly.

To improve loading times, I have assigned each image a "data-src" attribute containing its actual source. Then, when a specific category is selected (clicked), I update the source attribute of all images in that category by looping through them.

Here's an example of how I structure my HTML:

<img loading="lzay" class="post_image" data-src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg">

In my JavaScript code, I iterate through the selected images within a for loop like so:

for(i = 0; i< selection.length; i++){
            let data_src = selection[i].children[2].getAttribute("data-src");;
            selection[i].children[2].src = data_src;
        }

I am now facing a challenge where I need to determine when all the images from a particular category have finished loading. Even though there is additional code that should execute after the for loop finishes, I want to ensure that it only runs once every image in the category has loaded onto the page.

Answer №1

Here's a quick solution I put together for you. Give it a try and see if it does the trick. Let me know if you encounter any issues.

index.html

<img id="pic1" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg"/>
<img id="pic2" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg"/>
<img id="pic3" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg"/>
<script type="text/javascript" src="app.js"></script>

app.js

const pic1 = document.getElementById("pic1");
const pic2 = document.getElementById("pic2");
const pic3 = document.getElementById("pic3");

const picsArray = [
  pic1,
  pic2,
  pic3
]

let picsLoaded = 0;

for (let j = 0; j < picsArray.length; j++) {
  picsArray[j].onload = function () {
    picsLoaded++;
  }
  if (picsLoaded >= picsArray.length) {
    // All images have been loaded successfully
  }
}

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

Sorting data in a Footable table by an unfinished line

My data table contains various lines like: 97.5%, 10/30, 41 RPM, 3.6 seconds, $4750, $100 When I set the type data-type = "number" in the rows, everything is stripped except for the numbers. However, I need the output to remain complete as shown in the ex ...

I'm unable to resolve the issue regarding the message "Property or method is not defined on the instance but referenced during render."

I have a good grasp on what the issue is (the inputs I'm trying to v-model aren't declared), but for some reason, I can't resolve it (or figure out how to) even after studying other posts with the same problem. After comparing my code with ...

Unable to attach eventName and callback to addEventListener due to the error message stating 'No overload matches this call'

I am attempting to attach an event listener to the input element stored within a class method. This method takes a props object containing eventName and callback. public setTextFieldInputListener({ eventName, callback }: TextFieldListenerProps): void { ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

ngRepeat does not iterate through an array

Presented below is an object: { "_id" : ObjectId("5454e173cf8472d44e7df161"), "questionType" : 0, "question" : "question1", "answers" : [ { "content" : "answer1" }, { "is_true" : "true", ...

importing a text file into the appropriate input field on an HTML form

I've been experimenting with this JavaScript code and I can't seem to get it to work as intended. The code is designed to save the value of a single textbox into a text file that can later be loaded back into the same textbox. However, I'm f ...

Having trouble choosing a subitem from a dropdown menu in Vuejs?

An example can be found at https://jsfiddle.net/79epsrmw/. However, the issue arises when targeting the item1 sub-menu in VS Code even after assigning a unique id. var app = new Vue({ el: '#app', data: { menuItems: [ ...

Using jQuery, how can I dynamically change the stacking order of an element when clicked?

I'm struggling to change the z-Index on button click. I have a static image and a dynamic div, and I want to send the #imgDiv1 behind the static image. Unfortunately, despite trying everything, I haven't been able to achieve this. You can check ...

Improving the functionality of the JavaScript key press function

I have a small javascript snippet on my website that allows me to navigate the site using the arrow keys on my keyboard. document.onkeydown = function(evt) { evt = evt || window.event; switch (evt.keyCode) { case 37: ...

Instructions for printing a page and closing the Print window using Selenium

New to using Selenium: I tried the following code in Selenium to open the print window, but unfortunately it doesn't seem to work Keyboard keyboard = ((HasInputDevices)driver).getKeyboard(); keyboard.pressKey(Keys.ENTER); keyboard.pressKey(Keys.ch ...

Utilize CSS properties to pass as arguments to a JavaScript function

Is there a way for me to make my CSS animation functions more efficient? I have similar functions for different properties like height, width, and left. Can I modify the function below to accept a CSS property argument instead of hardcoding height? Window ...

What could be causing the sluggishness of this ajax call?

After implementing an ajax function on the page load event, I noticed that there was no record of the call in the server log (which logs all entrance and exit points of all MVC server methods). The request from the JavaScript to the server was taking an un ...

Guide to retrieving fresh information from an API using a desktop application built on node and electron

Looking for advice on efficiently retrieving new order data from the Shopify API for a private desktop application I'm working on. Should I query the API at regular intervals while the application is active, or is there a way to implement webhooks in ...

Implement dropdown menus for category selection in Magento CE version 1.8.1.0

A previous option causing confusion has been removed * UPDATE * I am trying to set up a dropdown list for easy navigation through a specific category hierarchy. If you need a visual example, check out this image: * UPDATE * I'm still on the hunt ...

Searching for $or command in express.js

Is it possible to use $or in the app.get() function of an express.js application? For example, how would I write a find() query that includes $or like this: db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } ) I'm curious about ...

Transforming dates from JSON and showcasing them on a DataTable

I'm facing an issue with my local JSON file where the dates are being rendered in a DataTable as /Date(1350028800000)/ (10/12/2012). I came across this thread which talks about converting the date format, but I need help figuring out how to implement ...

Creating a .env file using Vanilla JavaScript to securely store and conceal tokens

I am currently working on a vanilla JavaScript project. Within the app.js file, I am making an API call to retrieve specific values. Initially, I tested the API using Postman by including all the necessary headers there and then implemented the code in my ...

Having trouble determining why the design is not displaying correctly

I'm currently working on a calendar webpage, and everything looks perfect until I add the new JavaScript element. Suddenly, the numbers in the first row start behaving strangely. I've tried to troubleshoot but can't seem to figure out what&a ...

Using Spring 3.0 with Jackson: How to post a composite entity using AJAX and JSON

Currently, I am utilizing spring 3.0 along with ajax and JSON in my work. The main domain class that I have is as follows: public class WebSite { int id; String description; SimpleType type; //getters and setters ... //... } The SimpleType class ...

Practical steps for programmatically adding or removing md-disable-backdrop in md-sidenav

Can the md-disable-backdrop attribute be removed from HTML? The issue arises when opening the side navigation as the md-sidenav does not have the md-disable-backdrop attribute. After making a selection from the form displayed in the side navigation, I now ...