Detect the size of the href file of a link by using JavaScript


Would like to write a script to detect the file size of the target of a link on a web page.

Right now I have a function that finds all links to PDF files (i.e. the href ends with '.pdf') and appends the string '[pdf]' to the innerText. I would like to extend it so that I can also append some text advising the user that the target is a large file (e.g. greater than 1MB).


Some web servers may give you a Content-Length header in response to a HEAD request. You could potentially use an XmlHttpRequest to send the HEAD request and see what you get.

Here's what one of my IIS servers says about a PDF file:

HTTP/1.1 200 OK
Content-Length: 127791
Content-Type: application/pdf

However, anything that's not delivered directly by the web server (a file served by PHP or, for example) won't work unless the script specifically handles HEAD requests.