Computer >> Computer tutorials >  >> Programming >> Javascript

How to do image preloading with javascript?


You can prefetch images using JavaScript using the following method −

function preloadImage(url) {
   let img = new Image();
   img.src = url;
   return img;
}

Note that all browsers will release(garbage collect) the image after some seconds if you haven't used it. To avoid this, keep a reference to the img object.