Loading images in advance with AJAX for enhanced AJAX performance

My website is structured in a sequential manner, where page1.html leads to page2.html and so on. I am looking to preload some images from the third page onto the second page. After searching, I came across this amazing code snippet:

$.ajax({
    url      : 'somePage.html',  
    dataType : "html",
    success  : function(data) {

        $(data).hide().appendTo('#someDiv');

        var imagesCount = $('#someDiv').find('img').length;
        var imagesLoaded = 0;

        $('#someDiv').find('img').load( function() {
            ++imagesLoaded;
            if (imagesLoaded >= imagesCount) {
                $('#someDiv').children().show();
            }
        });

        var timeout = setTimeout(function() {
            $('#someDiv').children().show();
        }, 5000);
    }                     
});

While this code effectively loads all contents of page3.html onto page2.html, I only want to load the images and have them hidden until the user navigates to page3.html. The issue with the above snippet is that it brings along other elements such as audio. So my question is, would this modified version below meet my requirements?

$.ajax({
    url      : 'page3.html',  
    dataType : "html",
    success  : function(data) {

        var imagesCount = $(data).find('img').length;
        var imagesLoaded = 0;

        $(data).find('img').load( function() {
            ++imagesLoaded;
            if (imagesLoaded >= imagesCount) {
              //halt? do something?
            }
        });

    }                     
});

Once again, my goal is to preload images from page3.html onto page2.html. Do you think this approach will work? And how can I conduct a test to confirm?

Answer №1

In your situation, the easiest method would be to utilize jQuery.get and specify the images or other objects you wish to preload.

For instance,

$.get('images/image1.jpg');
$.get('images/image2.jpg');
// and so on

This approach allows you to indicate which images from the next page should be preloaded in the browser.

The $.get function is essentially a shortened form of the $.ajax function. In this scenario, you're simply fetching the images to ensure they are cached in the browser. Therefore, when you navigate to the following HTML page, the images will already be loaded.

Verification Process

If you were to insert the provided code snippet into your page2 and then access that page with the Network tab open in Firebug or Chrome dev tools, you would observe that GET requests are made for the images and they are cached in the browser.

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

Looking to update the location of an element within a canvas using Vue and socket.io?

I am currently developing a 2D pong game using vue.js and socket.io. At the moment, I have a black rectangle displayed in a canvas. My goal is to make this rectangle move following the cursor of my mouse. The issue I am facing is that although my console l ...

The Error Message: "404 Not Found - Your Form Submission Could Not

Greetings, I am currently immersing myself in learning NodeJS and the Express framework. However, I have encountered an issue when attempting to submit a form that is supposed to go to the '/users/register' URL. It appears that my app.js is unabl ...

My navigation bar is giving me a bit of trouble, as there are two separate issues that seem to be interconnected

Looking for some help with my navigation bar layout. You can also check out the code on fiddle http://jsfiddle.net/SgtRx/ (should have done this earlier, sorry). I'm a beginner when it comes to coding, so please bear with me if I make any mistakes. ...

Array Filtering with Redux

I have come across similar queries, but I am still unable to find a solution. While typing in the search box, the items on the screen get filtered accordingly. However, when I delete a character from the search box, it does not show the previous items. For ...

What steps can I take to ensure that a user is unable to like a photo multiple times even after refreshing the browser?

I am currently exploring ways to replicate a similar like system found on Instagram. Specifically, I want to create a system where if a user likes a photo and then attempts to like it again, it will be unliked - and vice versa. This behavior should persist ...

Firestore query failing to retrieve most recent data

I have implemented a route guard in Angular that validates a specific value in firestore before granting access to the designated route. The component is accessed only after an HTTP cloud function has finished executing. This cloud function generates an o ...

Unable to retrieve the most recent global variable value within the confirmation box

<script type="text/javascript"> var customDiv ="hello"; $(function () { var $form = $("#authNotificationForm"); var startItems = $form.serializeArray(); startItems = convertSerializedArrayToHash(startItems); $("#authNoti ...

Trouble linking JavaScript and CSS files in an Express App

Could someone assist me in understanding what is causing my code to malfunction? Why is it that my javascript and css files do not execute when the server sends the index.html file to the browser? I have a simple setup with an html page, javascript file, ...

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

Experience the thrill of receiving a triumphant notification upon submission of your form

I'm currently learning about jquery and how to use it with ajax to insert and display data in a mysql table. I've been trying out some code that inserts and displays records from a mysql database. Right now, my goal is to make the success message ...

Discovering the position of elements in relation to their (grand^N)parent

Among my possessions are elements A and B. B has the ability to exist as a direct child of A, or there may be anywhere from 0 to N elements separating them. It is imperative that I determine how B is situated in relation to A, specifically noting the dist ...

Assigning attributes to inner components in VueJS based on prop values

Experimenting with some common VueJS syntax, but I am struggling to get this Button.vue SFC to function properly: <script setup> defineProps({ ... href: String, ... }); </script> ... <template> <Link :href="href&quo ...

Creating a schema for a JSON element in KendoUI: A simple guide

Looking for assistance on writing the schema for a JSON object with specific structure. { sev: [{ t: "t1", v: v1 }, { t: "t2", v: v2 }], sum: [{ te: "te1", ve: ve1 }, { te: "te2", ...

The $.Get method does not retain its value within an each() loop

When using the jQuery each() method on a DropDown select, I iterate through an li element. However, my $.get() function takes time to fetch data from the server, so I use a loading image that toggles visibility. The issue is that the each() method does not ...

Implementing Mouse Scroll Click Functionality in ASP.NET with C# (Without JavaScript)

How can I add a Mouse Scroll Click (Middle Button) event in ASP.NET and C#? I have already looked into the MouseWheel Event, but it did not provide the solution I was looking for. This is the order in which mouse events occur: MouseEnter MouseMo ...

Issue encountered: The function car.reviews.find() is not recognized

Encountering an issue with the find() method in my MERN stack application. I am looking to implement a reviews route where users can add comments about cars within the app. In the frontend, fields and buttons have been added; meanwhile, a post request has ...

Tips on transferring the id value from a modal window to an ajax click event?

I'm having trouble passing the image ID to AJAX for updating it in a modal window. After opening the modal and grabbing the correct ID, I attempt to pass it to AJAX but it shows as undefined. How can I properly pass the ID for further processing? $( ...

Trouble with background image displaying on meteor platform

Hey there! I'm in the process of replicating the HBO login page without functional links, but for some reason, the background image isn't loading properly. I suspect it might be an issue with resizing the image, but I can't pinpoint the exac ...

Prevent the SVG mouseclick event with CSS styling

Is it possible to prevent clicking on an SVG element using CSS? .disabled{ pointer-events: none; } After selecting the SVG element with $(".dasvg"), the console confirms the selection: [ <svg width=​"500" height=​"500" class=​"dasvg">​ ...

The child user interface component is failing to respond to keypress events within the parent component in an Angular project

I am facing a challenge in adding a keyboard shortcut to open a nested child UI Tab component through a keypress event. However, the Child nested tab can only be loaded after the Parent component is loaded first. Below is the structure of the UI tree: |-- ...