jquery asynchronous image loading technique

Can images be loaded asynchronously while the page is loading? The images will only be displayed when a user clicks on a button, rather than immediately showing up. As a result, I am curious if it's feasible to preload the images in a cache so that they can be quickly displayed when needed without delay.

Answer №1

All image elements are loaded asynchronously by modern browsers.

Check out this simplified image loader script that preloads multiple images and triggers the start() function when all images are fully loaded:

// image loader

// store image paths in the imageURLs array
var imageURLs=[];  
imageURLs.push("myImage1.png");
imageURLs.push("myImage2.png");

// the loaded images will be stored in the imgs array
var imgs=[];

var imagesLoaded=0;
loadAllImages(start);

function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesLoaded++; 
            if (imagesLoaded>=imageURLs.length ) {
                callback();
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}

function start(){

    // the imgs array now holds all fully loaded images
    // the order of images in imgs matches that of imageURLs

}

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

Executing a JavaScript function within the HTML body and passing a variable as an argument to the function

I recently created the following HTML code: <html> <title> Upload Infected File </title> <body> <header id = "header"> <h1 align="center">Upload Malware File</h1> <p align="center"> Pleas ...

Is there a way to align my two tables next to each other using CSS?

.page { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; } .items { float: left; } .secondItem { vertical-align: text-top; float: right; } .page-header table, th, td { border: 1px solid; display: block; background-color: ...

index.html: using jquery for selecting colors

I attempted to integrate a jQuery plugin into my application, but it doesn't seem to be working. In the head section of my code, I have included: <link rel="stylesheet" media="screen" type="text/css" href="./style/colorpicker.css" /> <script ...

Exploring the HTML5 File API: Features and Capabilities

After looking into the File API, I'm curious about when all major browsers will fully support it: Firefox has supported it since version 3.6 Chrome since version 8.0 What about Opera and IE? Is the File API meant to replace flash-based uploaders li ...

Utilizing Node and Electron to dynamically adjust CSS style properties

Having a dilemma here: I need to access the CSS properties from styles.css within Electron. Trying to use document.getElementsByClassName() won't work because Node doesn't have document. The goal is to change the color of a specific div when the ...

Type content in HTML5

Can you help me with a simple question? I am currently working on building my portfolio using html https://i.stack.imgur.com/rxYRS.png I want to be able to click on an image and add the description of my choice. Right now, it is showing something else: ...

Troubleshooting the issue of autoplay not functioning in HTML5 audio

I'm facing a strange issue with my code - the autoplay feature for audio is not working as expected. Typically, whenever I insert this particular piece of code into a website, the music starts playing automatically. However, it seems to be malfunctio ...

Is there a way to allow only the block code to shift while keeping the other span tags stationary?

Is it possible to change the text without affecting other span tags in the code? I want to make sure only this specific text is updated. How can I achieve that? var para_values = [ { content: "BRAND " }, { content: "MISSION" } ]; functi ...

Concealed Separator for Text Elements in HTML

I am in search of a method to distinguish certain specific strings within HTML code. Although I can recognize the desired strings, they may also appear as part of longer strings throughout the document. In order to locate them, I currently insert a special ...

Parallax Effect Slows Down When Scrolling In Web Page

Currently in the process of creating a website with a scrolling parallax effect using Stellar.js on the header and three other sections. However, I'm experiencing lag when scrolling, especially at the top of the page. I've attempted to reduce la ...

Creating a custom dynamic favicon and title in NextJS

Hello there! I am in the process of creating a web constructor. Currently, my application functions as follows: I verify the URL that the user is visiting (such as localhost:3000) I identify their project name within my web constructor (localhost:3000 -&g ...

What is the best way to incorporate scripts into the HTML of my Google Apps Script or Google Sheets?

I'm having trouble getting my Apps Script-based HTML to include any scripts. My doGet function for the HtmlService is working fine: function doGet() { return HtmlService.createHtmlOutputFromFile('myhtmlfilename'); } Regardless of whether ...

Is it possible to showcase a notification as a popup or alert in Django?

I'm working on a form in Django that redirects to itself after submission. I want to show a message saying "You have entered (work_area)" as a popup or alert that users can close. However, my current setup only displays the message within the HTML aft ...

Connecting CSS auto-complete with JSP content within Eclipse

Is there a way to connect the CSS autocomplete with the content of a JSP page? For instance, if I have an element like <div id="myid"> in the JSP file, can Eclipse auto-complete "myid" when typing "#" in the CSS file? I am aware that NetBeans has th ...

"Revolutionizing the way we navigate: Angular's innovative

Presently, my focus is on incorporating route transitions into my project. I've employed a component that appears on click and triggers the corresponding service function: routeTransition(destination) { if (this.router.url !== destination) { t ...

How to Remove onFocus Warning in React TypeScript with Clear Input Type="number" and Start without a Default Value

Is there a way to either clear an HTML input field of a previous set number when onFocus is triggered or start with an empty field? When salary: null is set in the constructor, a warning appears on page load: Warning: The value prop on input should not ...

a new webpage beginning from a different location

Starting from scratch here, I must apologize for not providing any code upfront. The issue at hand is this - I've got a page full of information sorted by ID (retrieved from the database). These IDs are linked from another page where users can click ...

Utilizing Python to manipulate the 'select' tag in HTML

Currently, I am attempting to retrieve events from an HTML page located at In my efforts to choose different areas using python script, I encountered a challenge with the following snippet of HTML code: <select data-ng-options="key as value.name for ( ...

Specifying file types in an HTML upload form

Is there a way to restrict my form so that it only allows jpeg files? Currently, it is displaying all types of files. <input name="image" type="file" /> Also, are there any JavaScript functions available for showing progress? ...

I would like to know the method for inserting an HTML element in between the opening and closing tags of another HTML element using

Recently, I came across a coding challenge involving a textbox. <input type="text></input> The task was to insert a new span element between the input tags using jQuery, as shown below: <input type="text><span>New span element< ...