Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if i use jQuery syntax : $("<img src='img.jpg'>") , will the image actually be downloaded to the client?

Tags:

jquery

syntax

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?

like image 865
Peeyush Kushwaha Avatar asked Nov 03 '12 09:11

Peeyush Kushwaha


2 Answers

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.

like image 175
Guffa Avatar answered Oct 18 '22 16:10

Guffa


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.

like image 44
Alnitak Avatar answered Oct 18 '22 16:10

Alnitak