sir-haver
sir-haver

Reputation: 3592

React: load images in advance

My server is a bit slow and when displaying even small size images, you can see them loading on screen, and I would like them to be displayed right away.

Thankfully I have a landing page which then after pressing a button, redirects to the main page which contains the images.

This routing is controlled in my app.js which is like the root file. This file routes to the landing page and to the main page. I thought that I could just load the images there and then pass them as props via the router, to the main page:

import projectImage1 from './assets/1.png';
import projectImage2 from './assets/2.png';
import projectImage3 from './assets/3.png';

class App extends Component {
  render() {
    return (
      <Route render={({location}) => (
        <TransitionGroup>
        <CSSTransition
          key={location.pathname === '/' ? location.key : null} // Use transition only if on landing page
          timeout={800}
          classNames="fade"
        >
          <Switch location={location}>
            <Route path="/" exact component={Landingpage} />
            <Route path="/app/:name" exact render={(props) => <MainApp
              projectImage1={projectImage1}
              projectImage2={projectImage2}
              projectImage3={projectImage3}
            />} />
          </Switch>
        </CSSTransition>
      </TransitionGroup>
      )} />


    );
  }
}

As you can see my MainApp.js received the 3 images as props. This is technically working without errors but I'm still seeing the images loading on screen. Why is it so? How can I load them in advance so that they can be displayed smoothly?

Thanks

Upvotes: 2

Views: 3799

Answers (1)

Anders Stensaas
Anders Stensaas

Reputation: 749

The browser doesn't load resources before it needs by default. For images this is when the image itself is visible. This is due to performance, but there is a way for you to load these images beforehand.

If you do this in your componentDidMount lifecycle method in your App component, the browser will load the images:

class App extends Component {
  componentDidMount() {
    const imagesToBePreloaded = [projectImage1, projectImage2, projectImage3]
    imagesToBePreloaded.forEach(image => { new Image().src = image })
  }

  render() {
    // [...] Removed for abbreviation.
  }
}

Upvotes: 4

Related Questions