How to set src to the img tag in HTML from another domain?

To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load. With HTML, you can add the image source as another domain URL by setting the src attribute to point to an external domain.

Syntax

<img src="https://external-domain.com/image.jpg" alt="Description" width="200" height="100">

Key Attributes

Attribute Description
src The URL of the image (can be from any domain)
alt Alternate text displayed if image fails to load
width The width of the image in pixels
height The height of the image in pixels
loading Controls when the image loads (lazy, eager)

Example: Loading Image from External Domain

<!DOCTYPE html>
<html>
  <head>
    <title>External Image Example</title>
  </head>
  <body>
    <h2>Image from External Domain</h2>
    <img src="https://picsum.photos/300/200" 
         alt="Random image from Picsum" 
         width="300" 
         height="200">
    
    <h3>Another External Image</h3>
    <img src="https://via.placeholder.com/250x150/0066cc/ffffff?text=Sample+Image" 
         alt="Placeholder image" 
         width="250" 
         height="150">
  </body>
</html>

Important Considerations

CORS and Security: Most image URLs work directly, but some domains may block external access. Always test your external image URLs.

Performance: External images depend on the other domain's server speed. Consider loading="lazy" for images below the fold.

Reliability: External images can break if the source domain changes or removes them. For critical images, consider hosting them locally.

Using JavaScript to Set External Image Source

// Set image source dynamically
let img = document.createElement('img');
img.src = 'https://picsum.photos/200/150';
img.alt = 'Dynamic external image';
img.width = 200;
img.height = 150;

document.body.appendChild(img);

// Change existing image source
let existingImg = document.getElementById('myImage');
if (existingImg) {
    existingImg.src = 'https://via.placeholder.com/300x200/ff6600/ffffff?text=Updated';
}

Conclusion

Loading images from external domains is straightforward using the src attribute with a full URL. Always include alt text and consider performance implications when using external image sources.

Updated on: 2026-03-15T22:25:23+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements