Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Image preload React

import { useEffect } from 'react';

declare global {
  interface Window {
    usePreloadImagesData?: Record<string, unknown[]>;
  }
}

export const usePreloadImages = (imageSrcs: string[]): void => {
  useEffect(() => {
    const randomStr = Math.random().toString(32).slice(2) + Date.now();
    window.usePreloadImagesData = window.usePreloadImagesData ?? {};
    window.usePreloadImagesData[randomStr] = [];
    for (const src of imageSrcs) {
      // preload the image
      const img = new Image();
      img.src = src;
      // keep a reference to the image
      window.usePreloadImagesData[randomStr].push(img); 
    }
    return () => {
      delete window.usePreloadImagesData?.[randomStr];
    };
  }, [ imageSrcs ]);
};
Comment

How to preload images in React.js?

/*
Supposing you have pictures: string[];
- array of pictures urls defined in your component's props.
You should define componentDidMount() 
method in your component and then just create new Image object for each picture you want to be preloaded:
*/
componentDidMount() {
    this.props.pictures.forEach((picture) => {
        const img = new Image();
        img.src = picture.fileName;
    });
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: nodejs mysql error handling with user example 
Javascript :: react rating stars component 
Javascript :: Referrer Policy: strict-origin-when-cross-origin angular 
Javascript :: get date in milliseconds javascript 
Javascript :: request-promise-native error RequestError: Error: unable to verify the first certificate 
Javascript :: input tag data fetch html javascript 
Javascript :: gsap keyframes 
Javascript :: slice string javascript 
Javascript :: slice() in javascript 
Javascript :: node express tutorial 
Javascript :: javascript get user from api 
Javascript :: on:click svelte arguments 
Javascript :: prettier overrides 
Javascript :: #{} js 
Javascript :: how to hide footer in specefic pages in react router 
Javascript :: sequelize update index column 
Javascript :: random number generator 
Javascript :: localstorage syntax 
Javascript :: socket-client-io for reconnection in js or javascript 
Javascript :: app running in expo client is slow 
Javascript :: install react hotjar 
Javascript :: how to print hello world in javascript 
Javascript :: js findindex 
Javascript :: use the whatwg url api instead 
Javascript :: copy array of object in js 
Javascript :: return new Promise(res = { 
Javascript :: material ui change icon size on xs screen 
Javascript :: make input bigger if text does not fit 
Javascript :: javascript eingabe in inputfielder übernehmen 
Javascript :: back to top scroll animation jquery 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =