简体   繁体   中英

Bootstrap carousel: Make download next image when using background-image on div instead of img

Prequel: I am using Bootstrap Carousel . Since I want to use background-size: cover, I am using a div with background-image set, instead of the default .

The issue: For some reason, the carousel doesn't seem to preload the next image. When I click next image, I can see the image being downloaded. Unfortunately, I think because of this lack of preloading the images aren't getting the right size (Set by JS) in some browsers:

Anyway to make it preload all the images in the carousel?

This seems to work great. Just place this with your images in the url() outside of the carousel.

#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }
#preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }
#preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }

Credit: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Create a class for eg .preload hide it using display: none; as it will not only hide element but also remove its impression on page(height/padding/margin/etc).

after that create div with .preload class. <div class="preload"></div> below <body> tag. That will force it and its child elements to get loaded before anything below gets loaded.

Now you can add your images using tag into the div and it will load initially but won't display in preload div.

Refer below code for better understanding:

CSS: .preload{ display: none; } .preload{ display: none; }

HTML

<div class="preload">
<img src="preload-this-img-1.jpg" />
<img src="preload-this-img-2.jpg" />
<img src="preload-this-img-3.jpg" />
</div>

Note: Search engines may not be happy with loading one image two times and not using alt="" in image tag, I will update with solution for it, if found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM