In JavaScript, new Image
is a way to create a new instance of the Image object.
The Image object represents an HTML image element, which can be used to display images on a web page. When you use new Image
, you create a new instance of this object that you can then manipulate with JavaScript.
One common use case for new Image
is preloading images. By creating an instance of the Image object and setting its src attribute to the URL of an image file, you can force the browser to download and cache the image before it’s needed on the page. This can improve performance by reducing the delay between when the user requests an action (such as clicking a button) and when an image is displayed.
Here’s an example:
const myImage = new Image();
myImage.src = 'https://example.com/my-image.jpg';
This creates a new instance of the Image object called myImage
, sets its src attribute to 'https://example.com/my-image.jpg'
, and starts downloading the image from that URL. Once the image is downloaded, it will be cached by the browser so that it can be displayed quickly when needed.
You can also use other properties and methods of the Image object to control how images are loaded and displayed on your web page. For example, you might use myImage.onload
to execute code once an image has finished loading, or set myImage.alt
to provide alternative text for screen readers.