mooc-course.com is learner-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Show Photo in Javascript?

Displaying images dynamically using JavaScript is a crucial skill for web developers. This article explores various methods to show photos in JavaScript, ranging from simple DOM manipulation to more sophisticated techniques. Whether you’re building an image gallery, a social media feed, or enhancing your web pages with dynamic content, these techniques will prove invaluable.

Read more: How to Remove Script tag from HTML String in Javascript?

How to Show Photo in Javascript?

  • Learn multiple approaches to displaying images with JavaScript
  • Understand the pros and cons of each method
  • Gain insights into which method is most efficient for different scenarios
  • Improve your web development skills with practical, real-world code examples

Method 1: Basic DOM Manipulation

The simplest way to display an image using JavaScript is by manipulating the DOM.

function showImage(src, alt) {
    const img = document.createElement('img');
    img.src = src;
    img.alt = alt;
    document.body.appendChild(img);
}

showImage('https://example.com/photo.jpg', 'A beautiful landscape');

Pros:

  • Simple and straightforward
  • Works in all browsers
  • No dependencies required

Cons:

  • Limited control over loading behavior
  • No built-in error handling

Efficiency: Good for simple use cases, but lacks advanced features.

Method 2: Using the Image Object

The Image object provides more control over the loading process.

function loadAndShowImage(src, alt) {
    const img = new Image();
    img.onload = function() {
        document.body.appendChild(this);
    };
    img.onerror = function() {
        console.error('Failed to load image:', src);
    };
    img.src = src;
    img.alt = alt;
}

loadAndShowImage('https://example.com/photo.jpg', 'A beautiful landscape');

Pros:

  • Better control over loading process
  • Built-in error handling
  • Can preload images before displaying

Cons:

  • Slightly more complex than basic DOM manipulation

Efficiency: More efficient than Method 1 due to better loading control and error handling.

Method 3: Using the Fetch API and Blob URLs

For more advanced use cases, you can use the Fetch API to load images and create Blob URLs.

async function fetchAndShowImage(src, alt) {
    try {
        const response = await fetch(src);
        const blob = await response.blob();
        const objectURL = URL.createObjectURL(blob);
        
        const img = document.createElement('img');
        img.src = objectURL;
        img.alt = alt;
        document.body.appendChild(img);
        
        img.onload = () => URL.revokeObjectURL(objectURL);
    } catch (error) {
        console.error('Failed to fetch image:', error);
    }
}

fetchAndShowImage('https://example.com/photo.jpg', 'A beautiful landscape');

Pros:

  • Greater control over the loading process
  • Can handle cross-origin requests more easily
  • Allows for image manipulation before display

Cons:

  • More complex implementation
  • Requires modern browser support

Efficiency: Highly efficient for complex scenarios, especially when dealing with large images or when image manipulation is required.

Method 4: Lazy Loading with Intersection Observer

For improved performance, especially with multiple images, lazy loading is an excellent approach.

function lazyLoadImage(src, alt) {
    const img = document.createElement('img');
    img.dataset.src = src;
    img.alt = alt;
    
    const observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.src = entry.target.dataset.src;
                observer.unobserve(entry.target);
            }
        });
    });
    
    observer.observe(img);
    document.body.appendChild(img);
}

lazyLoadImage('https://example.com/photo.jpg', 'A beautiful landscape');

Pros:

  • Improves page load time and performance
  • Reduces unnecessary data usage
  • Works well for long pages with many images

Cons:

  • Requires modern browser support
  • More complex setup

Efficiency: Most efficient for pages with multiple images, especially for improving initial load time and performance.

Efficiency Comparison

  1. Basic DOM Manipulation: Simplest but least efficient for complex scenarios.
  2. Image Object: More efficient than basic DOM manipulation due to better loading control.
  3. Fetch API and Blob URLs: Highly efficient for complex scenarios and large images.
  4. Lazy Loading: Most efficient for pages with multiple images and optimizing overall page performance.

The most efficient method depends on your specific use case:

  • For simple, one-off image displays, Method 1 or 2 is sufficient.
  • For complex image handling or manipulation, Method 3 is ideal.
  • For pages with multiple images and performance optimization, Method 4 (Lazy Loading) is the most efficient.

By understanding and applying these techniques, you can significantly improve your web applications’ image handling capabilities, enhancing both user experience and performance.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free Worldwide Courses

Learn online for free

Enroll in Multiple Courses

Learn whatever your want from anywhere, anytime

International Language

Courses offered in multiple languages & Subtitles

Verified Certificate

Claim your verified certificate