Programmatically Load Image in JavaScript
- 1 minute read
Images can be loaded with JavaScript, and you can perform an action right after an image has been loaded:
const img = new Image();
img.onload = () => {
// do something
};
img.src = `https://picsum.photos/200`;
Once the image has successfully loaded, it won’t be fetched each time you reference it in your HTML:
<img src="https://picsum.photos/200" alt="A sample image">
One practical use case is showing a placeholder such as a spinner while an image loads.
Conclusion
Anyway, hopefully you found this useful!