hzane
hzane

Reputation: 13

If you remove() an img tag w/ jquery, will the browser still try and retrieve it?

If the img src points to a non-existent file, will that prevent a 404 in your cache?

Thanks!

Upvotes: 0

Views: 187

Answers (4)

Jashwant
Jashwant

Reputation: 29005

  1. I am not sure what you are asking, but you will load img in dom, browser is going to fetch it, even if its display:none. (Not sure about every browser, but its the way to cache images in slideshows)

  2. Also, once you load it on your dom, no matter you remove it, it will be there on your cache.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707476

By the time any of your javascript runs to remove the image from the DOM, the image tag has already been parsed and the request to load the image URL has at least been queued and perhaps already sent.

It would be browser-specific behavior for whether the browser would be smart enough to abort the image load if it had not yet completed when the image tag was removed. It may have already even completed.

You should realize that javascript cannot modify the DOM until the DOM has been parsed. That means that things like image tags have already been set in motion before you have a chance to modify them with javascript. That's just a fact or limitation of the browser design.

If you control the HTML and you sometimes want a different image in that place, then it's better to NOT put the image tag in the HTML at all. When your code runs and determines which image it wants, then it can create the appropriate image tag and insert it into the DOM. Then, the browser will not spend any time loading an image you don't want.

If you don't care if you load an extra image and just want to make sure it doesn't display the wrong image before you set the right image, then mark the image tag as display: none or visibility: hidden until you've made sure the right img URL is in place and then you can make it visible. CSS is processed before the tags are parsed so it is applied as the tag is created.

Upvotes: 2

000
000

Reputation: 27247

Why not test it out?

Here's a fiddle: http://jsfiddle.net/atFtS/ and the source:

<img src="http://www.asdfghjkl.com/qwerty.png" style="display:none" />​

Open up your browser inspector (I'm using Chrome), go to the network tab, and see what happens.

It did try to load the image, even though it's not going to be rendered.

Here's another fiddle: http://jsfiddle.net/atFtS/1/ where I added:

$('img').remove();​

It still loaded the image and probably cached the 404 hit.

Upvotes: 1

DerektheDev
DerektheDev

Reputation: 103

Probably not. Javascript runs on document load, after all elements are ready.

Upvotes: 0

Related Questions