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.');
});
new Image() creates an HTMLImageElement. Assigning src starts the image request.
const image = new Image();
image.src = 'images/large-photo.jpg';
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);
});
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.
<!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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.