Preloading Images with JavaScript

You can create an image object in JavaScript and assign its src before the image is inserted into the document. The browser then starts fetching that image, which can make a later display faster when the resource is still available in cache.

const preloadedImage = new Image();
preloadedImage.src = 'images/large-photo.jpg';

preloadedImage.addEventListener('load', () => {
  console.log('Image is ready in the browser cache.');
});
Table of Contents

Create an Image object Top ↑

new Image() creates an HTMLImageElement. Assigning src starts the image request.

const image = new Image();
image.src = 'images/large-photo.jpg';

Know when the image has loaded Top ↑

If later code depends on the image dimensions or pixels being available, listen for its load event.

image.addEventListener('load', () => {
  console.log(image.naturalWidth, image.naturalHeight);
});

Display the preloaded image Top ↑

document.getElementById('preview').src = image.src;

The original tutorial connected this step to a button click. That interaction is preserved in the complete source below. Replace the example filenames with your own image paths.

Complete working source Top ↑

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Preload an image with JavaScript</title></head>
<body>
<img id="preview" src="images/placeholder.jpg" alt="Preview">
<button type="button" id="showImage">Show Image</button>
<script>
const imageUrl = 'images/large-photo.jpg';
const preloadedImage = new Image();
preloadedImage.src = imageUrl;

document.getElementById('showImage').addEventListener('click', () => {
  document.getElementById('preview').src = imageUrl;
});
</script>
</body>
</html>

This technique is related to image galleries and slideshows. Continue to the original JavaScript image slideshow tutorial.

Image Object




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer