Reputation: 3623
if i use jQuery syntax : $("<img src='img.jpg'>")
, will the image actually be downloaded to the client? or do i have to append it to body in order to download it?
Upvotes: 5
Views: 443
Reputation: 339816
Yes, the image will be downloaded immediately.
Even though the Image
element that has been created isn't in the DOM yet, your browser will still start downloading it as soon as the .src
attribute is set.
Using your own avatar, I just did this in the console:
> i = $('<img src="http://graph.facebook.com/100002351317104/picture?type=large">');
...
> i[0].width
180
showing that the image is indeed loaded.
If you think about it, this actually has to be the case otherwise image pre-loading could never work. Image pre-loading depends on creating a detached Image
node and setting its src
, which is exactly what $("<img src=...>")
will do.
Upvotes: 5
Reputation: 700312
You don't have to add the image element to the document for the image to be loaded.
The image element itself will request the image as soon as you create it (and as soon as it has a src
value).
Watch the net acivity (in Firebug/Developer Tools) when you run this: http://jsfiddle.net/Guffa/AvgVN/
Google "javascript preload" to find tons of code examples that uses this.
Upvotes: 6
Reputation: 74420
I would say yes, or maybe depends of browser.
$("<img src='http://crssrd.com/web_apps/index/themes/crssrd.com/images/loading.gif'>")
Test this on Chrome for example: http://jsfiddle.net/SMnhU/ Image is instantly downloaded.
Upvotes: 2