necolas / react-native-web

Cross-platform React UI packages
https://necolas.github.io/react-native-web
MIT License
21.68k stars 1.79k forks source link

Suggestion: A more reliable way to check if image is in the cache #2708

Open dominictb opened 3 months ago

dominictb commented 3 months ago

Is there an existing request?

Describe the feature request

Problem

Original issue: https://github.com/Expensify/App/issues/45853

Most of the time if the image is loaded once, it will be in the cache, and subsequent fetch for the same image URI will hit the cache. However, this implementation

https://github.com/necolas/react-native-web/blob/54c14d64dabd175e8055e1dc92e9196c821f9b7d/packages/react-native-web/src/exports/Image/index.js#L203-L212

indicate that if the initial state of the image will always be IDLE even if the image is loaded before.

Solution

We will modify the ImageLoader.has logic to be able to check reliably if the image is in the cache. It works both when the image URI is previously loaded by <img tag or by the Image component in react-native-web

let globalImageToCheckCache = new window.Image()
ImageLoader.has = (uri) => {
   globalImageToCheckCache.src = uri;
   let isInCache = globalImageToCheckCache.complete
    globalImageToCheckCache.src  = '' // unassign to avoid firing extra request
    return isInCache
}