I've seen a couple of pages load their javascript files into a page via new Image.src ='';
<script type="text/javascript">
new Image().src = "XXXX\/js\/jquery-1.7.2.min.js";
</script>
I was just wondering the benefits or purpose of this.
Downloading the libraryLocate the correct Javascript download of the library you want to install. Download the library and make a copy in your sketch folder. (If you're using the web editor, you can upload the relevant files using Upload file in the dropdown in the “Sketch Files” sidebar.)
Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .
JavaScript is known as the web development language. By using JavaScript, we can make our web page attractive by inserting images into it. By default, we use the <img> tag in HTML to display images. In the <img> tag, we have a method known as src , which helps get the source of the image that we gave to display.
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
defer
attribute which is intended for such purposes rather than the new Image()
hack."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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With