1

In React, is it possible to preload an image that is imported via JS import?

I would like a way to combine the following from my js file

import image from './image.svg';

and the following from my index.html file

<link 
        rel="preload"
        as="image"
        href="???/image.svg"
/>
Ben
  • 15,938
  • 19
  • 92
  • 138
  • Does this answer your question? [How to preload images in React.js?](https://stackoverflow.com/questions/42615556/how-to-preload-images-in-react-js) – André Teixeira Jan 27 '21 at 13:03
  • The solutions presented there appear to involve React itself via ComponentDidMount or similar. Using a method like that would mean the image would only get loaded well after React itself has been loaded. I would like it to load as soon as possible, hence why using the link in the head of the HTML. – Ben Jan 27 '21 at 14:32
  • I would suggest using react-helmet and check this question https://stackoverflow.com/a/67677453 – zero298 Jul 16 '21 at 23:54

2 Answers2

0

I don't know how about create-react-app but if you use your own webpack setup you can try something like:

  plugins: [

    new HtmlWebpackPlugin({
      ...
    }),
    new HtmlWebpackInjectPreload({
      files: [
        {
          match: /(filename)+.+(\.webp|\.png)$/,
          attributes: { as: 'image' },
        }
      ],
    }),
  ]

If you are using HtmlWebpackPlugin, you can try the HtmlWebpackInjectPreload plugin, which is the extension of the first one. It will look for outputted asset names and inject links into the head section based on those findings.

https://github.com/principalstudio/html-webpack-inject-preload

TwistedOwl
  • 1,195
  • 1
  • 17
  • 30
-1

You can use your imported image like this

<img src={image}/>

Since you import your image it will be loaded with the document.

MadeInDreams
  • 1,991
  • 5
  • 33
  • 64