Tips for loading all background images simultaneously

I just created my first website page with a few background images that crossfade.

However, I am experiencing an issue where the next background image takes some time to load during the crossfading effect if the page is not cached on the user's computer initially.

Does anyone have any ideas on how to preload all the images at once?

JSFiddle: https://jsfiddle.net/sawqo6j9/

var i=0;
var imghead=[
"url(http://www.psdgraphics.com/file/abstract-mosaic-background.png)",
"url(http://www.psdgraphics.com/file/colorful-triangles-background.jpg)",
"url(http://www.mrwallpaper.com/wallpapers/gradient-background.jpg)"
];

function slideimg() {
    setTimeout(function () {
        jQuery('body').css('background-image', imghead[i]);
        i++;
        if(i==imghead.length) i=0;
        slideimg();
    }, 6000);
}
slideimg();
html, body {
     height: 100%;
} 

body {
     background: url(http://www.psdgraphics.com/file/abstract-mosaic-background.png) no-repeat center center fixed;
    -webkit-background-size: auto 100%;
    -moz-background-size: auto 100%;
    -o-background-size: auto 100%;
     background-size: auto 100%;
    -webkit-transition: all 2s ease-in;
    -moz-transition: all 2s ease-in;
    -o-transition: all 2s ease-in;
    -ms-transition: all 2s ease-in;
     transition: all 2s ease-in;
     margin: 0;
     padding: 0;
    font-family: Arial;
    font-size: 14px;
    color: #fff;
    margin: 100px;
}
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <p>There goes page content</p>
  </body>
</html>

Answer №1

To improve the caching of background images, my preferred method involves preloading them off screen using the <img> tag and then removing the container once the page has finished loading:

#preload {
  position: fixed;
  top: 100%;
}

$(function() {

var imgUrls = [
    "//www.example.com/image1.png",
    "//www.example.com/image2.jpg",
    "//www.example.com/image3.jpg"
    ];

$.each(imgUrls, function() {

    $('#preload').append('<img src="' + this + '" alt="">');
});

$(window).on('load', function() {

    $('#preload').remove();
});
});

The #preload element can be included in the HTML markup or added dynamically with JavaScript:

$('body').append('<div id="preload"></div>');

Answer №2

You have the option to specify them in preload containers within your CSS.

#preload-01 { background: url("http://www.psdgraphics.com/file/abstract-mosaic-background.png") no-repeat -9999px -9999px; }
#preload-02 { background: url("http://www.psdgraphics.com/file/colorful-triangles-background.jpg") no-repeat -9999px -9999px; }
#preload-03 { background: url("http://www.mrwallpaper.com/wallpapers/gradient-background.jpg") no-repeat -9999px -9999px; }

Simply include them in your HTML code.

Check out this demo on Fiddle

UPDATE: Another approach is to insert them as images and then remove them once fully loaded using a .load() function.

var i=0;
var imghead=[
    "http://www.psdgraphics.com/file/abstract-mosaic-background.png",
    "http://www.psdgraphics.com/file/colorful-triangles-background.jpg",
    "http://www.mrwallpaper.com/wallpapers/gradient-background.jpg"
];

$(imghead).each(function(key,val){
    $('body').append('<img class="preloader" src="'+val+'">');
    $('.preloader').load(function(){
        $(this).remove();
    });
});

function slideimg() {
    setTimeout(function () {
        jQuery('body').css('background-image', 'url('+imghead[i]+')');
        i++;
        if(i==imghead.length) i=0;
        slideimg();
    }, 6000);
}
slideimg();

Explore the updated version on Fiddle

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

Animate a div to sense whether it has reached the top or bottom position

Is it possible for a div to animate when it reaches almost halfway while scrolling? I'm looking to achieve this effect on a sticky sidebar, similar to how it works on this website: sample This is the code I have: $(function(){ // document ready ...

Tips for making radio button selection mandatory in an HTML5 form

How can I require a user to select one radio button in an HTML 5 form before submitting it? I attempted to use the required attribute, but since there is no radio button group, how can I apply this requirement? <form action="/Home/Sendtitle" method=" ...

Tips for achieving full width design within a container

Hello everyone, I require some assistance. I am attempting to create a full-width navigation while being constrained by a wrapper div with a fixed width of 900. I am unsure of how to achieve this without creating an additional div like the header. I am see ...

Adjust grid column sizes automatically when a smaller number is declared - tailwind

I am working with the tailwind grid system and have specified 6 columns for each row. However, if the number of elements is less than 6, I would like it to resize them to 3. <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 grid-flow-r ...

What is the best way to add a character within a YouTube JSON link?

Fetching json data from a link, the youtube format in the link is http:\/\/www.youtube.com\/watch?v=UVKsd8z6scw. However, I need to add the letter "v" in between this link to display it in an iframe. So, the modified link should appear as ht ...

Combining several position-aligned classes into a single div instead of each having their own individual div

http://jsfiddle.net/58arV/ Trying to create a question component where users can choose the correct answer out of 4 options. I planned to use 4 input styles with a checkmark "radio" DIV on the right. When a user clicks on an option, it should display a c ...

Having trouble with JavaScript/JQuery not functioning properly in HTML content loaded using the load() method

My goal is to load an input form from a separate file called new_machine.php into my index.php. This form includes an input with a dropdown that retrieves options from a MySQL database and displays them as anchors. The issue arises when I attempt to manipu ...

What is the most effective method for populating an array with all images from a particular directory?

I recently installed a pdf viewer plugin on my website (check it out here: ), and I have a question regarding its functionality. I am looking to include approximately 60 - 70 pages in this flip book, but I am unsure of how to proceed. I have attempted var ...

Understanding JavaScript Regular Expressions

To ensure that no HTML tags are entered into a textarea, I am utilizing the following regex for validation. If any HTML tags are detected in the textarea, I need to display a validation message. The regex being used is: /<(\w+)((?:\s+\w ...

Styling Options for Material-UI Tables: Enhancing the Look of Your Table Components

I am working with 'material-ui' and attempting to change the color of a table element based on its value. In the code snippet below, I have tried to make the background color go red if the cell value is "Out of Zone". However, even though the tab ...

Using variables with Tailwind arbitrary values is not supported

Why is it that in tailwind, bg-[#5ad0a1] works but assigning the hex value to a variable such as const color = '#5ad0a1';, and then using bg-[${color}] does not work? <span className={`inline-flex items-center rounded-md bg-[${color}] px-2 py- ...

Centering the overlay gallery box in MonoBook Skin of MediaWiki using CSS

While working on transforming the MonoBook Skin into a DarkMode version, I encountered an issue with the gallery overlay css. The Overlay displays a semi-translucent white box with text at the bottom by default, overlaying the image. I made adjustments to ...

What are the strategies employed by Wix in utilizing mobile and desktop CSS?

While browsing through Wix, I stumbled upon something quite intriguing that left me puzzled. On a desktop with a width of 2560px, the Wix page loaded normally. But what caught my attention was when I resized the screen to make it smaller, either by using ...

Unable to achieve horizontal alignment with DIV element set as inline-block

Currently, I have five columns that are aligned using the display:inline-block. Everything seems to be working fine, but there's a peculiar issue that arises when I refresh the page multiple times. Occasionally, while the first column remains at the t ...

In situations where there may be a duplicate, what alternative can I utilize in place of the id attribute?

I understand that almost any element in the DOM can have an "id" attribute, and I've used it to track each client in a table of clients. Although ids should not be repeated, my rows are assigned unique identifiers based on each person's "clientId ...

Ways to initiate a transition upon clicking a button, causing it to switch from being hidden (`display: none`) to visible (`display: block`)

I'm attempting to create a smooth transition effect when a button is clicked, similar to a toggle function, where the content below it seamlessly shifts instead of abruptly moving. The classic example of this is the Bootstrap navbar hamburger menu, wh ...

Gradually fade with JavaScript

My JavaScript code below is used to recursively reload a specific DIV with the results of a data query. The issue I'm facing is that each time the DIV, identified by id="outPut", is reloaded, all the data fades in and out due to the fadeTo function. ...

How can I make an image fill the container with CSS zoom effect

My website features a full viewport image as the background beneath the Nav Bar. I am looking to achieve a specific effect on mobile where the image is zoomed in and centered without distortion, allowing some of it to still be visible as a background. The ...

Change the left position of the sliding menu in real-time

I am currently designing a website with a sliding menu feature. By default, the menu is set to -370px on the left, displaying only the "MENU" text initially. When a user hovers over the menu, it expands to the right, allowing them to select different menu ...

Manipulating the Datepicker onChangeMonthYear event in Jquery UI

I am currently working on customizing the appearance of specific dates within a jQuery UI datepicker. If a date is considered a holiday (meaning it matches a date in an array of specified holiday dates), I want to remove the default styling and make some m ...