Home > Enterprise >  Background image render slowly when im slide to the next image
Background image render slowly when im slide to the next image

Time:11-30

I have 4 images , every time the image change to the next image , it take some time when the image get full render (slow render) , the size of the images is 4-5mb , How can I make the image appear immediately?

import React, { useEffect, useState } from 'react'
import dataSlider from '../utils/dataSlider';

export function Slider() {

  const [currState, setCurrState] = useState(0)

  useEffect(() => {
    const intervalId = setInterval(() => {
      if (currState === 3) setCurrState(0);
      else setCurrState(currState   1);
    }, 5000);

    return () => clearInterval(intervalId);
  }, [currState]);
  

  const bgImgState = {
    backgroundImage: `url(${dataSlider[currState].url})`,
    backgroundPosition: 'center',
    backgroundSize: 'cover',
    height:'100%'
  };

  
  const goToNext = (currState) => {
    console.log('sss');
    setCurrState(currState);
  };

  return (
    <div className="slider-container">
      <div style={bgImgState}></div>
      <div className="description">
        <h2>{dataSlider[currState].title}</h2>
        <h1>{dataSlider[currState].subtitle}</h1>
      </div>
      <div className="bullets">
        {dataSlider.map((dataSlider, currState) => (
          <span
            className="bullet"
            key={currState}
            onClick={() => goToNext(currState)}
          ></span>
        ))}
        <small>0{currState 1}</small>
      </div>
    </div>
  );
}

this is how the image rendering

CodePudding user response:

Preload them...

function Slider(){
    dataSlider.forEach(i=>{
        var img=new Image();
        img.src=i.url;
    }
    //...
}

At the top of your component, you can loop through them and create a new image with the src planned to be used as background. This will load the picture even without having it in the DOM. If cache settings are correct server-side, the next time the browser gets requested to show the image, it will use the cache instead.

Note tough, that this might make the first image load time increase, since the browser will be loading other images at the same time.

  • Related