Skip to content
Advertisement

JS/React/Next load image from mirror after timeout

I have opted to host all of my images for a site on IPFS, they are pinned fine. This reduces traffic and costs from my hosting provider to within the free tier.

Sometimes the IPFS url does not load fast enough, as it depends on where the user is, and CDNs that claim to cache IPFS results have not been working for me (they don’t find my hash to cache)

So I wanted an alternative, I wanted to allow for some latency of loading the image from IPFS and then fallback to loading the image directly from my server.

It’s not just images, but basically it seems as if the src tags from a variety of resources should be conditionally filled in. Or perhaps a preloading script could try to load the resources and then timeout and load them in. I don’t want these resources downloaded from my server unless absolutely necessary, for this application and audience optimizing the theoretical loading speed of the site isn’t that important. Ideally I can do all of this in the frontend code. Has anyone loaded resources from mirrors, conditionally?

Advertisement

Answer

You could check if the image has not loaded after some time. Lets make a new component <ImageWithFallback>

const ImageWithFallback = ({src, fallbackSrc}) => {
   const [srcToUse, setSrcToUse] = useState(src)
   const imgLoadedOnInitSrc = useRef(false)


   useEffect(() => {
      const timer = setTimeout(() => {
          if (!imgLoadedOnInitSrc.current) setSrcToUse(fallbackSrc)
      }, 5000)

      return () => clearTimeout(timer)
   }, [])


   return <img src={srcToUse} onLoad={() => {imgLoadedOnInitSrc.current = true} />
}

However I wouldnt recommend this. What you are trying to do cant be done reliably on client. People on slow connections like mobile might fall back to your server, or people living far away. You cant tell if its the end user who has a slow connection, or the server. So you might get more requests to your server than you expect.

A more stable approach might be to do an initial request to both your server and the IPFS one and measure the latency and if the percentage difference is above a threshold, decide on the base hostname for all images. However…this then means this initial check also causes traffic on your server; and for users on slow connections, doing this itself will slow the page load.

Really, you need to having working reliable CDN.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement