react-nativeimagebackgrounddelay-load

ReactNative - ImageBackground load local image with a delay


I noticed that, when I run the react-native app, the images that I set as background using the tag <ImageBackground> load with a delay of almost 2 seconds, even if they are not heavy images (~100K) and they are stored in local.

I have also read this answer but it didn't solve my problem.

This is my simple code for insert an image as background:

<ImageBackground source={require('../images/ScanQR.png')} style={styles.backgroundImage}>
    <Text style={styles.domanda}>
      Example text
    </Text>
</ImageBackground>

Solution

  • You can require() the images inside of App.js to load them before. Do it like this:

    async function loadResourcesAsync() {
      await Promise.all([
        Asset.loadAsync([
          require('./assets/images/stock1.jpg'),      
          require('./assets/images/stock2.jpg'), 
          require('./assets/images/undraw1.png'), 
        ]),
        Font.loadAsync({
          // This is the font that we are using for our tab bar
          ...Ionicons.font,
          // We include SpaceMono because we use it in HomeScreen.js. Feel free to
          // remove this if you are not using it in your app      
          'open-sans-regular': require('./assets/fonts/OpenSans-Regular.ttf'),
          'open-sans-extrabold': require('./assets/fonts/OpenSans-ExtraBold.ttf'),
        }),
      ]);
    }
    

    I am using Expo here and you don't need to create this function, it's already inside of App.js, just add your images inside of require() function.

    I don't know if this would work in React Native without Expo.