Jquery problem with cached images having height and width of 0

Jul 08, 2011 22:17

So I managed to solve a major problem in jquery, an issue that apparently plagues many people.

When dynamically adding a new image, if the image is already cached, the browser has a habit of kicking back a value of zero when .width() and .height() are called on it. This can be especially annoying if the programmer is trying to resize the image dynamically, since no assessment of the image's real width and height can be ascertained.

My current script grabs all image links and all embedded image urls from the current dom, and makes an array of them. Links are no problem usually, since the image hasn't been loaded yet, but i found that after testing my chrome extension on a single page multiple times, I would eventually run into a point when the browser would decide the image was already cached, and would give me the problem that all embedded images already had. It would load, but with a width and height of 0. Terribly annoying.

I tried making a .load() function and that worked sometimes, but eventually there would be a problem again. and then I came upon the solution, I had to add a timestamp to the end of the image to grab a new image. But of course if the timestamp is added dynamically every time, then the images are never cached at all in a good or bad way. Then I figured it out. Since my script creates a large image list object, I added a timestamp when the image was added to the list. I couldn't add it to the link itself, because then matches couldn't easily be made on the links. By separating the timestamp, and adding it at time of load, it allows me to make sure my cache is dynamic, but i still get a local cache.

This solved my problem and hopefully it can solve someone else's.

jquery, coding

Previous post Next post
Up