Thursday, 14 October 2021

Confusions about different ways of displaying images from an external url using JavaScript

I recently learned there seem to be multiple ways to display an image on a web page.

The first way is to directly assign the URL to an image element's URL

const img = new Image();

img.onload = () => {
  document.querySelector("#myImage").src = url;
};
img.onerror = () => {};

img.src = imageUrl;

Another way I recently learned is using fetch

fetch(imageUrl)
    .then((response)=>response.blob())
    .then((blob)=>{
       const objectUrl = URL.createObjectURL(blob)
       document.querySelector("#myImage").src = objectUrl;
})

I have a few questions about both approaches:

  1. I am familiar with fetch but I normally use it to fetch JSON. The second way of using fetch to get the image seems to me like we are fetching raw binary data of that image file over HTTP, while the first one we are delegating the browser to kick off a Get request to fetch that image. But from the server's perspective, there are no differences in terms of how it sends the image down? Am I understanding this right?

  2. In what situations we should favor one approach over the other? I feel like the second approach is going to have a lot of CORS problems than the first one, but not sure exactly why.

  3. are there any other ways to display an image on a web page? I heard of base64 encoding/decoding a lot when people talk about images. Is base64 related to response.blob() i.e. the second approach? Or it is different? if so, can someone please give me an example of using base64 to show an image?

  4. lastly, I think displaying images has been a hole in my knowledge of frontend or web development. Please feel free to recommend any good resources on this subject.



from Confusions about different ways of displaying images from an external url using JavaScript

No comments:

Post a Comment