What should I do if one of my images fails to load after the previous one has loaded successfully?

My code is designed to create an animation using 3 canvases: one for the base image, one for the streamline wind map drawing, and another for an image covering part of the drawing. The following code displays the uploading of two images.

            var img = document.createElement("img");
            var cvrimg = document.createElement("cvrimg");
            img.src = "https://cors-anywhere.herokuapp.com/www.example.com/img.png";
            cvrimg.scr = "https://cors-anywhere.herokuapp.com/www.example.com/img-two.png";
            img.crossOrigin = "anonymous";
            cvrimg.crossOrigin = "anonymous";
            img.onload = function () {
                imgctx.drawImage(img, 10, 10);
                cvrimg.onload = function () {
                    console.log("maybe");
                    cvrctx.drawImage(cvrimg,10,10);
                    startDrawing(wdDataArr,wsDataArr,dataManArr,pastDataArr,onlineArr);
                }
            }

After adding some log statements to my code, I noticed that the cvrimg.onload function was not being called, and only one image was being queried in the network tab of the Chrome inspect tool.

Any tips or advice would be greatly appreciated by this aspiring programmer.

Thank you.

Answer №1

When img.onload is called, the function for cvrimg.onload is defined. However, if cvrimg loads before img.onload, the function will not be called because it is not yet defined.

Furthermore, creating an element with

cvrimg = document.createElement("cvrimg")
results in a nonsensical <cvrimg> element being created.

Option 1 – loading images in parallel

let img = document.createElement("img"),
    cvrimg = document.createElement("img");

img.src = "https://cors-anywhere.herokuapp.com/www.example.com/img.png";
cvrimg.scr = "https://cors-anywhere.herokuapp.com/www.example.com/img-two.png";

img.onload = function() {
    console.log("img loaded");
    ...
}

cvrimg.onload = function() {
    console.log("cvrimg loaded");
    ...
}

Option 2 – loading images in series

let img = document.createElement("img"),
    cvrimg = document.createElement("img");

img.src = "https://cors-anywhere.herokuapp.com/www.example.com/img.png";

img.onload = function() {
    console.log("img loaded, loading cvrimg now");
    cvrimg.scr = "https://cors-anywhere.herokuapp.com/www.example.com/img-two.png";
    ...
}

cvrimg.onload = function() {
    console.log("cvrimg loaded");
    ...
}

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

Adding a class to a navigation item based on the route path can be achieved by following

I am currently working on a Vue.js project and I have a navigation component with multiple router-links within li elements like the example below <li class="m-menu__item m-menu__item--active" aria-haspopup="true" id="da ...

What is the best way to retrieve an AJAX response in advance of sending it to a template when utilizing DATAT

Recently, I've been working on integrating log tables into my admin panel using the datatable plugin. Despite setting up an ajax call in my datatable, I'm facing issues with retrieving the response before sending it to the table. Here's a s ...

Angular 2 property accessor designed similar to Linq style

Many times, we come across an array (IEnumerable) property where we need to extract specific values. In C#, we can achieve this by using the following code snippet: public AssetModel PromoImage { get { return Assets.FirstOrDefa ...

In search of an effortless method to effortlessly select numerous elements using a handy bookmarklet

My goal is to develop a bookmarklet that can perform various functions on different webpages with ease. The concept involves placing it in a convenient location, such as the bookmark bar, and executing a "standard function" on a particular page. Instead of ...

Condense categories

Hello there, I'm currently working on a table that contains different groups, and I am trying to figure out how to collapse categories within my table. Check out the Plunker here This is the HTML code snippet I am using: <table border=1> ...

An issue occurred while attempting to execute a function in AngularJS

Currently, I am in the process of developing a cross-platform application using AngularJS, Monaca, and Onsen UI. My current challenge involves calling a function in my controller from an ng-click() event on my view. However, upon clicking the button that ...

the value contained in a variable can be accessed using the keyword "THIS"

I recently developed a snippet of code that adds a method to a primitive data type. The objective was to add 10 to a specified number. Initially, I had my doubts about its success and wrote this+10. Surprisingly, the output was 15, which turned out to be ...

Is it possible to trigger multiple button clicks using JQuery simultaneously?

Hello everyone, I am new to StackOverflow and this is my first question here. I hope it's not too silly. Thank you in advance for your help! I am trying to achieve a functionality where one button click triggers the clicks of multiple other buttons u ...

JavaScript - Retrieve a nested property within an object using an array of strings

I possess an object in the following format { metadata: { correlationId: 'b24e9f21-6977-4553-abc7-416f8ed2da2d',   createdDateTime: '2021-06-15T16:46:24.247Z' } } and I possess an array containing the properties I wish to re ...

Does React trigger a re-render when setState is called even if the state value remains unchanged?

Imagine I create a React component with an initial state of {random: 1}. Now, if I were to execute the following code: this.setState({random: 1}) Would this action result in triggering a re-render of the component? Furthermore, is there a method to avoid ...

Ensuring that a service is completely initialized before Angular injects it into the system

When Angular starts, my service fetches documents and stores them in a Map<string, Document>. I use the HttpClient to retrieve these documents. Is there a way to postpone the creation of the service until all the documents have been fetched? In ot ...

Having trouble with Lerna bootstrap? You might be running into the dreaded npm error code E401

Every time I run Lerna bootstrap on Jenkins, it fails with an error, but it works fine on my local machine. npm ERR! code E401 npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager" Package.json in the main folder ...

Is Joi's existence a myth?

I've been using Joi for validation, and I've encountered a situation that I'm having trouble with. I have an object that sometimes includes an id field (for editing) and other times it doesn't (for creating). My goal is to validate tha ...

Analyzing Varied Date Formats

I'm looking to create a function in AngularJS that checks if a given date is after today: $scope.isAfterToday= function(inputDate){ if(inputDate > Date.now().toString()){ return true; } else { return false; } } The iss ...

Error: The function Stripe.customers.cancel is not recognized in Stripe version 14.18.0

When executing Cypress tests that involve calling a cleanup function to remove users in Stripe, I encounter the following error: Body: { "status": 500, "message": "Error while cleaning the stripe test data", "error" ...

Transfer a script from a view to application.js in Rails: Guide and Instructions

After conducting some research, I found a code that worked well for me in the view. However, I am looking to transfer it to application.js so that I can utilize it in various forms. Another issue I encountered is having two scripts performing the same fun ...

JavaScript does not function properly with dynamically loaded content

Trying to load the page content using the JQuery load() method. See below for the code snippet: $(window).ready(function() { $('#content').load('views/login.html'); }); .mdl-layout { align-items: center; justify-content: center ...

Differences between utilizing computed variables versus useState and useEffect

Is there any downside to initializing a computed variable instead of using useState/useEffect to track it when its value can be fully derived from another property? Let's consider the following example: /** * ex paymentAmounts: [100, 300, 400] */ co ...

Send data from an AJAX request to a Laravel controller

Here is the code for my ajax request where I am trying to pass values to a controller in Laravel. var deviceid="<?php echo $id; ?>"; var day="<?php echo $day; ?>"; $.ajax({ 'async': false, 'global': false, url ...

Tips for implementing lazy loading for a section of a template in Angular 2

I have an Angular 2 component that has several sub-components within it. Some of these sub-components are expensive to load and may not always be necessary, especially if the user doesn't scroll far enough down the page. Although I am familiar with l ...