It's a quick and dirty way of initiating an HTTP request (as the comments on the question suggest).
There may be a minor advantage gained by initiating the download at the top of the page and then including <script src='the-same-file.js'></script>
at the bottom of the page so that the file can be loaded from the browser cache.
This might allow the latency of the download to be parallelized with a parsing task. For example, the download initiated in the head
might run while the body
is still being parsed.
Why not just reference the file in the head using the src
attribute?
If neither [the defer or async] attribute is present, then the script is fetched and
executed immediately, before the user agent continues parsing the
page.
Source (suggested reading)
In other words, this method attempts to allow the browser to download the file without incurring the blocking behavior until later in the process.
However
- If this is really necessary, I would consider the
defer
attribute which is intended for such purposes rather than the new Image()
hack.
- This "optimization" could backfire depending on cache headers. You could end up making two HTTP requests or even downloading the file twice.
"In the Wild"
A quick investigation of several major sites (Google search, Gmail, Twitter, Facebook, Netflix) shows that this technique is not used to fetch JavaScript files and used very sparingly overall.
For example, Facebook appears to use it not for caching/performance but for tracking purposes when the site is (potentially maliciously) loaded into a frameset. By creating an Image
instance and setting the source, they initiate an HTTP request to a page which tracks the clickjacking attempt.
This is an isolated case; under normal circumstances this script will never be run.