简体   繁体   中英

Loading images with XHR Request

I want to create an image progress-bar library so I need an event while loading images to update the progress-bar (eg onprogress )

Suppose I'm going to load all images with creating an XHR Request to have onprogress event, so I need to know is there any difference between these scenarios:

First:
1- Load images with XHR request
2- Append an img tag, points to the image url (eg <img src='boo.png' /> )

Second:
1- Load images with XHR request
2- Append an img tag with the base64 of XHR response (eg <img src='data:image/png;base64,==Ad3tr' /> )

Edit: Belatedly realized you weren't asking about IMG .vs. XHR image loading but, rather, two different approaches to using XHR. Keeping my original answer, below, since it has info about the IMG .vs. XHR differences that are probably still of interest here.

Briefly, there's a pretty big difference in terms of overall complexity. Using a data-url to put XHR data into an IMG object is a non-trivial problem - see this SO question . It relies on new APIs that may not be fully supported, and there are several performance implications: increased page load time to load the JS needed, CPU cycles needed to encode the response data, and additional time required to garbage collect all the extra memory needed.

I put together a jsperf test to compare the two approaches but note that the data-url test is incomplete(!) - it doesn't actually produce a valid URL, but it does utf8 + base64 so it's probably not-horrible for a comparison. But, if anything, it's faster than what you'll end up with.

Basically I can't think of any advantage to using a data-url, other than that it avoids having to rely on the browser cache... but I expect that's little more than a theoretical objection

With XHR-based image loading you're dealing with ...

  1. Limited support for fetching binary (image) data : The XHR responseType property is designed to allow this, but isn't available on all browsers. Thus, you'll need to look into workarounds there.
  2. Limited support for base64-encoding . IE9- doesn't support atob , thus you'll have to rely on a JS shim. This will have performance implications for both CPU and garbage collection, which may or may not concern you
  3. Limited support for fetching cross-domain resources . XHR requests have to be same-origin unless you implement server support for CORS . And, again, not all browsers (IE9-, no surprise) fully support CORS.

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