2

We're building a website in React. We want the background-image to cycle through an array of 10 different backgrounds. Right now we are using a divStyle that sets a background-image with a url that is updated every 10 seconds to request the next image. This works, however this causes a request to the server every 10 seconds. Is there a way to load an array of images once in the componentDidMount (so on loading the webpage for the first time) and then just cycling through this array?

We tried making an array with Image() objects, but the background-image property only accepts a url. We also tried rendering the array with Image() objects in the render method of React, but we then get a 'Object not valid as React child' error and in the console the object is displayed as <img src='/assets/img/bg1.jpg> without the closing '/' in the end of the tag.

Our loop to fill the array with Image() objects looks like this:

for (var i = 1; i <= imgNumber; i++) {
  imgArray[i] = new Image()
  imgArray[i].src = '/assets/img/bg'+ i +'.jpg'
}
kajdehoop
  • 517
  • 8
  • 22
  • It should only load them all once and then load them from the browser cache (ie second loop won't be going back to server) - unless you are actually doing something in your react code that fetches them from the server each time. – Pete Feb 01 '18 at 14:36
  • Now you've added some code, they aren't actually background images and my first comment still stands, the first loop would load them and the second time it goes around, they should be fetched from the browser cache – Pete Feb 01 '18 at 14:41
  • That seems logical indeed, but the images show up in the network tab of the chrome dev tools, even if they were loaded before – kajdehoop Feb 01 '18 at 14:43
  • 1
    it should say from cache: https://stackoverflow.com/questions/13140318/check-whether-network-response-is-coming-from-server-or-chrome-cache – Pete Feb 01 '18 at 14:44
  • I feel so stupid, thanks man! I have another related question: is it possible to pre-load the next background-image in the array? Right now there is a flickering in the transition when the images get cycled through for the first time, because the next image has not been loaded yet – kajdehoop Feb 01 '18 at 14:59
  • 1
    Running your loop above should be enough to preload them: https://stackoverflow.com/questions/3646036/javascript-preloading-images. Just make sure you do it before you start showing the images as backgrounds. Of course if they are too big, then you may still get a flicker as they are being rendered – Pete Feb 01 '18 at 15:09
  • Thank you, that works perfectly! – kajdehoop Feb 01 '18 at 15:51

0 Answers0