say I have an image hosted externally, say on imgur, then on my site in my html I can have:
<img src="https://i.imgur.com/hDEXSt7.jpg">
and it shows the image. Even though the image is hosted externally, it's not a CORS violation to do that.
Now, before I load/display that image, I want to first check it's filesize.
On the backend, I can do this no problem with a HEAD request to the URL. But if I try to send an AJAX HEAD request from the FE, it's blocked as a CORS violation. Which makes sense, I know you generally can't do AJAX requests to external sites, for good reason.
But it seems awfully silly that with JS I can generate the HTML for displaying the image and insert that into the page such that it then must then make a call to an external website to get the image data, but I can't just ask how much data is there. Surely there must be a way.
This:
https://stackoverflow.com/questions/6575159/get-image-dimensions-with-javascript-before-image-has-fully-loaded\
is pretty close to what I want, but it's for the dimensions of the image. I want the filesize. <img>
elements don't seem to have a property for that. Also that seems like a weird hack where you start loading the image and get its info before it's finished. Ideally I'd like to get the filesize info before I start loading, so I can use it to decide whether or not to load the image.
I can do this by making the HEAD request from my own backend, but I'd rather not. The information I want isn't even on my backend. That just feels like such a silly waste of a call to my server just to get around the CORS restriction, given that CORS isn't going to stop me from actually going ahead and loading the whole image.
Any ideas?