• Resolved hommealone

    (@hommealone)


    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 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Phil Ewels

    (@tallphil)

    Hmm, this should be possible with the relatively new feature of prefetching images in the HTML header I think.. See https://css-tricks.com/prefetching-preloading-prebrowsing/#prefetching

    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: https://github.com/ewels/CPT-Bootstrap-Carousel

    Phil

    Thread Starter hommealone

    (@hommealone)

    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 */
    		image_tags.push(img_tag); 
    	});
    	/* add the image tags into the off-screen div */
    	$('.preload').append(image_tags);
    }
    preloadCarousel();
    
    Plugin Author Phil Ewels

    (@tallphil)

    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?

    Yup!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Preload carousel background images?’ is closed to new replies.