Preload Background Image

Preloading CSS Images

I can confirm that my original code seems to work. I was casually sticking to an image with a wrong path.

Here's a test : http://paragraphe.org/slidetoggletest/test.html

<script>
var pic = new Image();
var pic2 = new Image();
var pic3 = new Image();
pic.src="images/inputs/input1.png";
pic2.src="images/inputs/input2.png";
pic3.src="images/inputs/input3.png";
</script>

Preload background images

You could preload them using CSS like:

body::after{
position:absolute; width:0; height:0; overflow:hidden; z-index:-1;
content:url(https://placeimg.com/1640/1480/any) url(https://placeimg.com/1640/1481/any) url(https://placeimg.com/1640/1482/any) url(https://placeimg.com/1640/1483/any);
}

NOTE: You could use an array of images in the JS code and change them based on the index i.

var duration = 2500;var delay = 500;var i = 0;var images = ['https://placeimg.com/1640/1480/any', 'https://placeimg.com/1640/1481/any', 'https://placeimg.com/1640/1482/any', 'https://placeimg.com/1640/1483/any'];
setInterval(function() { $(".myimage").css("background-image", "url(" + images[i] + ")"); i++;}, duration + delay)
.myimage {  height: 500px;  width: 500px;  transition: background-image 1s linear;  background-image: url('https://placeimg.com/1648/1488/any');  background-size: cover;}
body::after { position: absolute; width: 0; height: 0; overflow: hidden; z-index: -1; content: url(https://placeimg.com/1640/1480/any) url(https://placeimg.com/1640/1481/any) url(https://placeimg.com/1640/1482/any) url(https://placeimg.com/1640/1483/any);}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="myimage"></div>

Preloading background images

I would do something like this. loadImages returns a Promise that will resolve once all of the images are loaded. The .then attached to it calls cycleImages, which starts up the interval. Since you will need the URLs in the JS anyway to do the pre-loading, instead of class switching I'm directly manipulating the background-image, that way you can remove the image URLs from the CSS and save a few redundant bytes. This also makes it easier to expand the list of images in the future too, you only need to add an item to the array of images instead of maintaining a complicated if statement.

function loadImages (images) {  // each image will be loaded by this function.  // it returns a Promise that will resolve once  // the image has finished loading  let loader = function (src) {    return new Promise(function (resolve, reject) {      let img = new Image();      img.onload = function () {        // resolve the promise with our url so it is        // returned in the result of Promise.all        resolve(src);      };      img.onerror = function (err) {        reject(err);      };      img.src = src;    });  };
// create an image loader for each url let loaders = []; images.forEach(function (image) { loaders.push(loader(image)); });
// Promise.all will return a promise that will resolve once all of of our // image loader promises resolve return Promise.all(loaders);}

// the images we are going to displaylet myImages = [ 'http://www.gifpng.com/400x200', 'http://www.gifpng.com/400x200/ffffff/000000', 'http://www.gifpng.com/400x200/000000/ffffff'];
// $(document).ready(fn) is deprecated,// use the $(fn) form instead$(function() {
// after the images are loaded this will be called with an array of the loaded images function cycleImages (images) { let index = 0; setInterval(function() { // since we need an array of the image names to preload them anyway, // just load them via JS instead of class switching so you can cut them // out of the CSS and save some space by not being redundant $('#backgrounds').css('backgroundImage', 'url("' + images[index] + '")'); // increment, roll over to 0 if at length after increment index = (index + 1) % images.length; }, 750); }

// load the images and start cycling through them after they are loaded loadImages(myImages).then(cycleImages).catch(function (err) { console.error(err); });});
#backgrounds {  height: 200px;  width: 400px;  border: 1px solid #000;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="backgrounds"></div>

How to make background images load faster

You don't want to use a placeholder image to prioritize your background images in situations like this, you want to use <link rel="preload">. That will tell the browser to start downloading the image as soon as possible.

Try adding the following code to the <head> of your page, and then use your background image as normal. It should load much faster:

<link rel="preload" as="image" href="images/header-img.jpg">

You can read more about this technique here:

  • Preload critical assets to improve loading speed
  • Preloading responsive images

Preload image to change css background from a url link

This updated code now works, using img.src as the background URL for the CSS refreshes the image as needed. Using just the image variable as the URL does not.

$('document').ready(function(){
var x = 0;
loadImage(x);
});

function loadImage(x) {
x +=1;
var image = new Image()
image.src = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x;

setTimeout(function() {
imgSwap(image, x);
}, 30000)
}

function imgSwap(image, x) {
$('body').css('background-image', 'url(' + image.src + ')');
loadImage(x);
}

PreloadJS to pass to background-image

You can not pass an image instance to CSS. CSS uses a string, so you could use the item's original source instead:

var imgSource = preload.getItem("background").src;
$('.main').css('background-image', 'url(' + img + ')');

Note that if you load the image using XHR (the default in PreloadJS), it may not pull from the cache, and instead load again. If you see this issue, I recommend using tag loading instead:

preload = new createjs.LoadQueue(false, 'img/');

Cheers.



Related Topics



Leave a reply



Submit