简体   繁体   中英

Changing an <img>'s src attribute and dispaying the new image _as it loads_

I'm displaying images like this:

<img src="placeholder.jpg" data-url="/get_image/{{image.id}}/" />

/get_image/{{image.id}} returns some JSON with the URL to the actual image, and then I replace the src attrivute of the <img> tag using jQuery.

The problem I have is that the image is displayed on the browser only when it's been completely downloaded. For large images, this can take a while and some users are thinking that the image is never loading, despite the fact that placeholder.jpg says "Loading..."

It would be great if the image that's replacing the placeholder would actually visibly load (for instance top to bottom like most JPEGs) as opposed to just suddenly displaying when all of it has been downloaded.

A way to show a progress bar would be even better.

Does anybody have suggestoins?

You can use preloader, but still should wait for image to load completely.

Other solution relies on how you saved the images.

You can open the image in an application like photoshop and when saving the file, click on the PROGRESSIVE option(Progressive option will make the image viewable even if it is not completely loaded).

In Photoshop:

  1. Open the image
  2. Click on the File -> save For Web ... (or Save for Web and Devices on previous versions)
  3. On the upper right part of the opened dialog, choose the 'JPEG' format
  4. You will see some options, choose 'Progressive'
  5. Save

This option will make the file slightly bigger in size, but the browser will show the images as they load.

Rather you can add image attribute 'title' or 'alt' value as ' Loading .... '

as title or alt property get displayed to user if image is about to load.

after image get loaded using Javascript you can change the alt or title value.

this is a basic solution. you can use it until you find proper solution.

Your question is very similar to my question where I discovered a solution which worked for me. It is unclear if it will work for you though because commenters have suggested it is dependent on the image being saved with the progressive option enabled.

For my case, the initial image always showed as it loaded and so my solution seemed to utilize that. For your case, if you were to initially load your big file first as a testcase and it appeared as it was downloaded, then I suspect my solution would also work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM