Nitish Kumar
Nitish Kumar

Reputation: 316

Image Compression when fetching from remote server

I have a JavaScript client application that uses another organization's APIs to fetch data. Now there's lots of images those url are sent via the API.

However the images are too large, i.e, bulky in size around 1MB each. If I put the image url in img tag, then the page slows when loading up as there are hundreds of images needs to be shown at page render.

Is there any way to compress the image at client end, cause my API are providers have just said no to send compressed image urls.

Upvotes: 2

Views: 2134

Answers (2)

Anoop Mc
Anoop Mc

Reputation: 88

I agree with Mosè Raguzzini's answer

Compressing the image in the front-end is not always suggested.

You should compress/ optimize the images before sending to the client side. The page is slow since its taking time to get the content from API only. I assume that you are not using showing the image using data:/ as you have mentioned you are using URL in the image tag.

You could do the following as well.

  1. Even though the other organizations API is not able to compress it you can create some back-end API which will do it for you or there are third-party tools available as well.
  2. Load image when its required (Lazy load) Please refer this URL for more info https://stackoverflow.com/search?q=Lazy+loading+images+javascript

Upvotes: 2

Mosè Raguzzini
Mosè Raguzzini

Reputation: 15821

The approach of this kind of problem usually involves lazy loading of images. The approach could be:

  • Load only the images that are in the frame of your view, wait to load the next images until scroll reaches them
  • Load image on demand (on click, hover and so on)

Although you can compress images client side, this will not avoid to download them from the server (100 img = 100MB in your case)

There are a lot of npm packages that lazy load components (and thus images) for you, like this

Upvotes: 2

Related Questions