How to Load Image From URL in JavaScript

Shraddha Paghdar Feb 02, 2024
How to Load Image From URL in JavaScript

Today’s post will teach about loading images from specified URLs in JavaScript.

Load Image From URL in JavaScript

The HTML element of the image tag embeds a photo/image in the document. The src attribute carries the direction to the photo/image you need to embed.

Src is the URL of the image required for the image element.

In browsers that support srcset, src is treated like a candidate image with a 1x pixel density descriptor unless an image with that pixel density descriptor is already defined in srcset or srcset contains w descriptors.

The following is the list of image file formats most commonly used on the web.

  1. APNG - Animated Portable Network Graphics
  2. GIF - Graphics Interchange Format
  3. PNG - Portable Network Graphics
  4. WebP - Web Picture format
  5. SVG - Scalable Vector Graphics
  6. JPEG - Joint Photographic Expert Group image
  7. AVIF - AV1 Image File Format

Formats like WebP and AVIF are recommended as they work much better than PNG, JPEG, and GIF for both still and animated images. WebP is widely supported in Safari, while AVIF is not supported in Safari.

SVG is still the recommended format for images that must be drawn accurately at various sizes. You can find more information in the documentation for the image.

Let’s understand it with the following example.

<input type="text" value="helloworld" id="imageName"/>
<input type="button" id="insert-btn" value="Insert" />
document.getElementById('insert-btn').onclick = function() {
  const val = document.getElementById('imageName').value;
  const src = 'https://google.com/images/' + val + '.png';
  let imgTag = document.createElement('img');
  imgTag.src = src;
  document.body.appendChild(imgTag);
}

We have defined the input element within the above example where the user can dynamically enter the value for a specific image. You can give a select dropdown instead of an input option and change the image based on user choice.

Once the user hits the button, get the user choice and create the img element for the document. Set the location or path of the image as the src attribute and append the image element to the existing DOM as a child.

Demo

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Related Article - JavaScript Image