Tips on improving image loading speed in JavaScript code

I'm working on a simple weather map that changes the background image depending on the current weather status. However, I've noticed that there is a delay in changing the image when the weather status changes. I'm wondering if this delay is due to how my code is structured or if there is another issue causing it. Can you suggest ways to improve the performance and make the image change faster?

form.addEventListener("submit", getData);

function getData(e){
    e.preventDefault();
    const link = 'http://api.openweathermap.org/data/2.5/weather?q=';
    const cityInput = input.value;
    const apiId = '&appid=12345667889&units=metric';
    const xhr = new XMLHttpRequest();

    xhr.onreadystatechange = ()=>{
      if (xhr.readyState == 4 && xhr.status == 200) {
        const object = JSON.parse(xhr.response);
        country.textContent = object.sys.country;
        city.textContent = cityInput;       
        humid.textContent = object.main.humidity + "%";
        temp.textContent = object.main.temp;
        wind.textContent = object.wind.speed + "mph";
        let snrise = object.sys.sunrise;
        let snset = object.sys.sunset;
        let dtrise = new Date(snrise*1000);
        let dtset = new Date(snset*1000);
        let risehrs = dtrise.getHours();
        let sethrs = dtset.getHours();
        let risemnts = "0" + dtrise.getMinutes();
        let setmnts = "0" + dtset.getMinutes();
        sunrise.textContent = risehrs + ' : ' + risemnts.substr(-2) ;
        sunset.textContent = sethrs + ' : ' + setmnts.substr(-2);
        const weatherName = object.weather[0].description.slice(0,17);
        status.textContent = weatherName;

        switch(true){
            case weatherName.includes("rain"):
                bgImg.src = "./images/rain.jpg";
                break;
            case weatherName.includes("clouds"):
                bgImg.src = "./images/clouds.jpg";
                break;
            case weatherName.includes("snow"):
                bgImg.src = "./images/snow.jpg";
                break;
            case weatherName === "mist":
                bgImg.src = "./images/mist.jpg";
                break;
            // Add other cases here for different weather conditions
            default:
                bgImg.src = "./images/pexels-photo-39811.jpg";
        }
      }
    }
    xhr.open('GET', link + cityInput + apiId, true);
    xhr.send();
}

Answer №1

When you use bgImg.src, the browser immediately searches for that image either in the cache (which is faster) or on the internet, causing a delay in loading.

Instead of this, ensure that the image is fully loaded before setting the bgImg.src to the loaded resource.

let icon = "";

if(weatherName.includes("rain")){
   icon = "./images/rain.jpg";
} else if(weatherName.includes("clouds")){
   icon = "./images/clouds.jpg";
} // and so on...

const img = new Image();
img.addEventListener('load', () => bgImg.src = img.src);
img.src = icon;

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 best way to include two class names within a single div using Next.js?

Struggling to include two different CSS classes into a single div element, I encountered some issues. For reference, here is a screenshot: https://i.stack.imgur.com/UuCBV.png https://i.stack.imgur.com/sHNwq.png My code snippet looks like this: blog.js ...

Ensuring the proper sequence of operations within a jQuery ajax callback function

I am facing an issue with my jQuery ajax function. The callback function includes two actions: 1) Taking the ajax result (which is an html form) and inserting it as the inner html of an html span. 2) Submitting this form How can I make sure that the form ...

Having trouble figuring out how to load images into a div based on the current page location?

Looking for a solution to my problem - I have a navigation bar with a fixed div (A) on the far right side. The nav bar remains at the top of the page. There are 6 sections in the body of the page, each being 1200px tall divs. What I want is for a different ...

When attempting to change an image using JavaScript, the image fails to load

I am having trouble understanding what is wrong with my code. <html> <body> <script type="text/javascript"> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { ...

Tips for accessing a DOM element's ::before content using JavaScript

Is there a way to retrieve the content of a DOM element's ::before pseudo-element that was applied using CSS3? I've attempted several methods without success, and I'm feeling very confused! // https://rollbar.com/docs/ const links = docum ...

Adjusting the value of a user form with multidata in PHP and Javascript

I am looking for guidance on how to modify the value of an input in a form that contains multiple data entries. Here is my form: <form method="post" action="pax-flight.php#pax-flight" class="paxform"> <input type="hidden" value="{"data":{"us ...

What is the best way to extract attribute values from a CodeIgniter calendar using the Ajax success result?

I am working with the codeigniter calendar to display events. Initially, when I generate the calendar and show each event, everything works fine. Each event can be displayed in a bootstrap modal based on the day that is clicked and passed to my controller ...

Developing a table with JavaScript by parsing JSON data

Starting off, I am relatively new to working with JavaScript. Recently, I attempted to generate a table using data from a JSON file. After researching and following some tutorials, I successfully displayed the table on a web browser. However, I noticed tha ...

What is the method for displaying the delete icon, a child component located within the Menu Item, upon hovering over it using Material UI CSS syntax?

My goal is to display the delete icon when hovering over a specific menu item that is being mapped using the map function. The desired functionality is for the delete icon to appear on the corresponding menu item when it is hovered over. I attempted to i ...

What is the best way to send JavaScript data to PHP?

Is it possible to post a variable to a PHP script without refreshing the page? If so, how can this be achieved? Here is an example using jQuery: $.ajax({ url: "myphpfile.php", type: "post", data: json/array/whatever, success: function(){ ...

Insert the META tag data specific to Facebook Instant Articles directly within the JavaScript code

My website is running on a custom-built CMS provided by a company, and it seems like a modified version of WordPress. They are unwilling to include a basic meta tag in our HTML code. I am looking for guidance on how I can incorporate Facebook's Insta ...

Locating discord.js users who possess multiple roles

Here is my code in its entirety as I have received some confusion on other forums: I am working on creating a Discord bot that can list users with a specific role. The plan is to create an array of roles, compare user inputs to the array, and display user ...

Passing Props from _app.js to Page in ReactJS and NextJS

I recently made the switch from ReactJS to NextJS and am encountering some difficulties in passing props from _app.js to a page. My issue lies in trying to invoke a function in _app.js from another page. In ReactJS, this process was simple as you could cr ...

Is there a way to execute a tanstack react query externally, as I am unable to utilize useQuery within the component?

const fetchSurveyData = useQuery(["survey"], () => getSurveyData({ page: 1, userLangCode: langCode, sortColumnName: "Date", sortColumnOrder: "DESC", country, ip, }) ); After tr ...

Avoiding the creation of a history entry while switching languages on a Next.js website

I'm currently developing a Next.js project that includes a language dropdown feature for users to choose their preferred language. In the existing setup, we are utilizing the router.push method from next/router to update the language selection and red ...

steps for transferring a shallow copy of an array to a function

How can I adjust this code so that when I press each button, the console.log displays a different slice of the array instead of always showing me the last 20 elements? for (var i = 0; i < array.length; i++) { var b; var NewArr = []; ...

Encountering an issue with Angular 1.6 and webpack: controller registration problem

Currently developing a small application with Angular for the frontend, and my frontend module is structured as follows: https://i.stack.imgur.com/tjfPB.png In the app.js file, the main Angular module 'weatherApp' is defined: angular.module(&a ...

creating an audio streaming application using child processes in nodejs

How can I effectively send a stream to a child process for streaming audio from a client to a server? I have successfully obtained the audio stream from a client. const ss = require('socket.io-stream'); const socketIo = require('socket.io& ...

Come back and display JSX

I am encountering an issue with a function that is supposed to add JSX to the variable markup. However, when the function is called, the markup is displayed as plain text instead of JSX. How can I ensure that the string is rendered as JSX rather than plain ...

Synchronous execution in Node.js: Best practices for coordinating tasks

While Node.js is known for its asynchronous nature, I am seeking to perform tasks in a sequential manner as outlined below: 1. Make an API request > 2. Convert the body from XML to JSON.stringify format > 3. Pass the string to a template. request.g ...