Support » Plugin: CPT Bootstrap Carousel » Preload carousel background images?

  • I’m using the background-image method. On the first run-through, there is a lag in displaying each image as it begins to slide. I believe this is because the background images are not loaded by the browser until the slide gets display: block.

    Is there an easy way to preload the background images? Maybe even lazy-load them one or two slides ahead?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Phil Ewels


    Hmm, this should be possible with the relatively new feature of prefetching images in the HTML header I think.. See

    So shouldn’t be too difficult to implement and inject this into wp_head() on pages showing a carousel, I think.

    Want to have a go? The plugin is open source:




    Interesting! So if you had say, six – or ten – images in your carousel, you’d inject a new link tag for each one into the head of the document?

    I resorted to a hacky javascript method of loading the images into a hidden div. Maybe it will help someone else until one of us gets the time to experiment with the prefetch link tags!

    /* preload slider images so they will be available to the slider with no blanks on the first run-through */
    /* without this, the background image does not become visible until the slide is fully visible, leaving gaps */
    function preloadCarousel() {
    	/* create an off-screen div to hold the preload images. Style it like this in your stylesheet: */
    	/* div.preload { position: absolute; left: -9999px; height: 1px; width: 1px; overflow: hidden; } */
    	$('body').append('<div class="preload" aria-hidden="true"></div>');
    	/* create an array to hold the img tags */
    	var image_tags = [];
    	$('.carousel .carousel-item').each(function() {
    		/* get the URL of each background image by getting the background-image style and stripping down to the URL */
    		var this_image = $(this).css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1');
    		/* create an img tag for each URL */
    		var img_tag = '<img src="' + this_image + ' alt="" /><br>';
    		/* add the img tag to the array */
    	/* add the image tags into the off-screen div */
Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.