Preloaded background images are loaded twice

I have a background image that I am preloading and caching, but my code is not reading it from the cache. It keeps loading the image as if it is not cached. Even though I have 8 images in the "imgSrcArray," I have simplified this example by hard coding just one.

Does anyone have any suggestions?

imgSrcArray = ["images/img0"]; 

//preload image
$.each(imgSrcArray, function (i, val) {
    $(function() { 
        $(document.body).append($("<img id='imgHid" + i + "'/>").attr("src", val).hide()) 
    }); 
});

$(document).ready(function(){
    $('#bkgrnddiv').css('backgroundImage', 'url(images/img0)');   
});

Answer №1

I have optimized the code for better performance and ensured that the image is loaded only once. It seems like the issue may have been related to repeatedly adding elements during the document load in the loop.

http://jsfiddle.net/Goepl/

var imageArray = ['http://placekitten.com/200/300'];

function preloadImages() {
    $.each(imageArray, function(index, value) {
            $('body').append($("<img id='hiddenImg" + index + "'/>").attr("src", value).hide())

    });
}

$(function() {
    console.log('Page fully loaded');
    preloadImages();
});

$(document).ready(function() {
    console.log('Document ready');
    $('#backgroundDiv').css({
        'background': 'transparent url(' + imageArray +') no-repeat 0 50%'
    });
});​

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

Ensuring one div remains in a fixed position relative to another div

I'm struggling to keep my two white divs aligned in relation to the black div in the center. They need to maintain the same distance from the black div even when the page is resized. #halvfjerds { width: 100%; height: 1050px; background-color ...

Achieve automated zooming out using highcharts-ng through code

Currently, I am using Highcharts-ng as seen on https://github.com/pablojim/highcharts-ng Upon inspecting the source code, I have noticed some interesting functionalities in the directive utilizing scope.$on which I can leverage for broadcasting. One examp ...

Bootstrap 4: The mystery behind why the popover fails to appear inside a scrollable dropdown

Is there a way to replicate the behavior of Bootstrap 3 dropdowns with scrollbars on hover and popovers in Bootstrap 4? It seems that setting overflow:hidden; for scrolling functionality in dropdown menus also hides the popover. I have tried using containe ...

Calculating the duration of time using JQuery with provided start and end times

I am currently utilizing a jQuery time picker to gather start and end times in a 12hr format. My goal is to calculate the time duration between the start and end times in HH:MM:SS format. The code snippet I have below is providing me with a duration like ...

Using ko.observableArray() with over 1000 <div> elements can lead to decreased performance

Please take a look at my jsfiddler for the example. http://jsfiddle.net/cYYEt/ If there is a different approach we should consider for binding or creating our array, that would be appreciated as well. I have managed to tackle this issue using either list ...

Is it possible for a MySQL loop to only delete the first entry?

My MySQL looping is not working properly when I click the second button to get their id and continue with the rest of the process. Why is this happening? $(document).ready(function() { $("#deleteSchedule").click(function (e) { e.preventDefault(); ...

Change the class of an element only within the div that is directly below it

Trying to achieve: Visit this link In my navigation menu, I have two folders with subpages under them. The CSS for displaying the page titles within the folder is as follows: .main-nav .subnav ul {display:none; transition: all 100ms ease-in-out; } .mai ...

Centralized and secure masthead

Currently, I am focusing on showcasing my portfolio at www.bbellmedia.com/mywork The specific requirement I have is to center the text 'Bryan Bell' and ensure that it remains fixed even when the user scrolls. Can anyone suggest the most effecti ...

How can I use jQuery to show the text value of a selected checkbox, dropdown menu, and flipswitch in a popup?

This form's HTML is set up for input with a popup display feature upon submission. Currently, only text can be displayed in the popup. It doesn't show the text of selected checkboxes or dropdown lists - just numbers for the dropdown and "ON" for ...

Duration of Animated Text

Despite trying various methods, I'm struggling to adjust the duration of my animations. I want each animated text to be displayed for 2-3 seconds, as they are currently moving too quickly. How can I resolve this issue? Please note that the specific pl ...

A step-by-step guide to adding a checkbox column dynamically within handsontable

I am currently utilizing handsontable within a jsfiddle at http://jsfiddle.net/kc11/cb920ear/1/. My task involves dynamically inserting a checkbox column before the existing data. The structure I am working with appears to be a multidimensional array, as s ...

HTML/CSS Top Bar: Position two contents at opposite ends of the top bar

I am attempting to design a top bar with the following layout Tel:4949494949 social media icons In the center, I want to display contact information and on the right side, my social media icons. However, ...

Chrome method for creating Flexbox columns of equal height

I am implementing a simple 2-column layout and I want to utilize Flexbox to ensure equal heights for the columns: HTML <div class="row flex"> <!-- menu --> <div class="col-xs-4"> <aside> Menu content wi ...

The Facebook JS SDK is causing an XSS error and returning a "user_denied" response, even though the Auth Popup for FB.Login is not being

I currently have a Facebook canvas app located at Previously, I was using an anchor link to direct users to the OAUTH login flow. After implementing the Facebook JavaScript SDK, I followed this logic: 1) Initialization of the FB API FB.init({ a ...

The replaceWith function in jQuery does not support <script> elements

I am faced with a situation where my AJAX response includes HTML code, including <script> elements. My goal is to replace an existing element with this HTML content. However, when I attempt to do so using the following code: $(element).replaceWith( ...

Creating a dynamic Google Chart by fetching data from MongoDB with AJAX/JQuery

After completing the MongoDB tutorial for nodejs on their website, I am in the process of creating a simple test case to send query results to a Google Chart using AJAX. Below is the nodejs code snippet used to form the query: CODE: var MongoClient = re ...

Make sure to blur all images whenever one of them is clicked

I am currently facing an issue with my webpage where I have 3 images displayed. I have implemented an event listener to detect clicks on the images, and once a click occurs on one of them, I want everything else on the page to become blurred, including the ...

Issue with draggable div containing gmap not functioning on mobile browsers

Is it possible to make a specific div draggable without dragging the content inside, such as a gmap widget? I have tried implementing this functionality in my code and it works on a computer browser but not on a mobile browser. Here is the simplified versi ...

Aligning a set of list items horizontally within an unordered list is a great way to maintain a clean

I'm struggling with centering the alignment of li elements within a ul. Below is the excerpt from my code: ul.nav { width: 1000px; margin: 0 auto; list-style-type: none; } .nav li { float: left; width: 300px; } #government { clear: left ...

Is it necessary to make multiple calls following a successful AJAX request?

Here is an AJAX call I am setting up. The first step is to hit the endpoint dofirstthing.do. Once that is successful, the next step is to make another call with "param1" as the query parameter. Now, my question is - how can I make a third call with "param ...