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

AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet: <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" req ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

"Encountering a hang while using the .save() function and only

Issue with storing data in MongoDB This is only my second attempt at saving data to a database and I am still relatively new to the process. I have a form on my HTML page that sends string data to be saved in a MongoDB database. I successfully connected t ...

What could be causing PHP to incorrectly display form data?

After learning html and css, I decided to venture into php scripting. My goal is to retrieve input from an HTML form using php code that looks like this: form.html : <html> <body> <form action="action.php" method="POST&q ...

What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me? function fu ...

Unlocking the Controller Action: Navigating from a Component Controller in Ember

I am currently trying to enhance the functionality of an Ember component. The specific component I am working on is located here: app / templates / programmers.hbs {{echo-hlabel-tf id= "id-test-hlabel" class="class-test-hlabel-mio" label="Horiz ...

Make sure to refresh the model using an Ajax request in Spring MVC

I have a page where I use AJAX to insert data into my database. On that same page, I display a table of records that are inserted. Each time I add a new record, I want to update the content of the table. Here is what I have implemented: @RequestMapping(va ...

What are some effective ways of using the parent, before, and children selectors?

<table> <tr><td><input type="text" value="123"></td><td><input class="here" type="text"></td></tr> <tr><td><input type="text" value="333"></td><td><input class=" ...

What's the reason the element inside the <div> is not displayed when a value is selected in the dropdown box?

I am perplexed as to why the element inside the does not appear when a value is selected in the drop down box. However, it works perfectly fine in JSFiddle: JSFiddle Below is my HTML code and Jquery script that functions properly in my own system: <t ...

Having trouble getting Firebase phone number authentication to work with Vue.js

I am currently in the process of developing a new Vue.js application using the Webpack template. Within this app, I have implemented a /sign-in route that displays a component named SignIn. To authenticate users, I am utilizing Firebase Phone Number authen ...

Please refrain from utilizing MUI - useGridRootProps outside of the DataGrid/DataGridPro component

When we click on "Filter" in the context menu of our DataGrid, we encounter this error. We are working on implementing a component hierarchy for the DataGrid as follows: MigrationJobTable.tsx: return ( <div data-testid='migrationJobTa ...

Disallow users from closing the tab or browser window

Is it feasible to create a loop on window.onbeforeunload that opens the current page repeatedly upon tab exit? Take a look at the code below - it works, but browsers may block it as a popup. window.onbeforeunload = function(e) { window.open(do ...

Retrieve distinct keys from a JSON file in Node.js

Below is an example of JSON data: [ { "Name": "User1", "primaryRegion": "US" }, { "Name": "user2", "primaryRegion": "US" }, { "Name": &q ...

What is the best way to add an element before every child in a react jsx render function?

Below is the code snippet I am working with: class MessageList extends Component { render () { return ( <ul> { this.props.messages.map((message) => { return <Message key={message.id} message={message} ...

How can one locate a particular element/style/class in the dev tools DOM while debugging in MUI v5?

Exploring the DOM and pinpointing the specific component file and style block in MUI v4 is a straightforward process: Locating a particular element/style class in MUI v4 However, in MUI v5, this functionality is no longer available, making it challenging ...

Newbie Question: What is the process to upload a website that consists of only HTML files to a web hosting provider

I'm embarking on creating a basic four-page website using HTML, CSS, and images. It's my maiden voyage into web design. When I finish developing the HTML files, what steps should I take to upload them and launch the website? ...

How come I am unable to save an array of objects in a State within React JS?

React JS component: When I make a request to the backend to fetch data stored in a MySQL table, it returns an array of objects. I store this data in a state called `favcoin`. However, when I console.log(favcoin), it displays an empty array [ ]. Strangely, ...

What method does the CSS standard dictate for measuring the width of an element?

In terms of measuring an element's width, Chrome appears to calculate it from the inner margin inclusive of padding. On the other hand, Firefox and IE determine the width of the box from the border, excluding padding but including the margin. Personal ...

Choosing the Laravel 6 option for editing via AJAX: A step-by-step guide

I am looking to update a user who resides in a specific state within a country. The country and state fields are dropdown select options, with a relationship established between them and the user. The state field is populated based on the selected country. ...

Navigating through web pages and creating dynamic interfaces is made simple

As someone relatively new to React, I am currently exploring how to integrate React Router with Material UI. In my Layout file, I have implemented a Navigation drawer from Material UI with the menu on the left and content on the right, as depicted in the ...