Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic generated image is requested twice when using jquery lazy loading in Google Chrome

I have an ashx file handler that generates my images.

<img src="www.mywebsite.com/action/getimage.ashx?imageID=f8be4bf6&width=100&height=700&bgcolor=999" />

This all works fine.

Now, I want to use lazy loading. Using this jquery lazy loading plugin

So i adjusted my html images like this:

<img src="imageplaceholder.gif" original-data="www.mywebsite.com/action/getimage.ashx?imageID=f8be4bf6&width=100&height=700&bgcolor=999" />

And added the following script:

$(function() {
   $("img").lazyload();
});

I noticed in the network tab of google chrome devoloper tools that there are two calls made to this filehandler.

I've created a testing fiddle here: link If you scroll down on this fiddle you'll see two image requests when the image is loaded in Google Chrome. In Firefox and IE this works with only one call.

Is there any way to avoid this behavior?

UPDATE:

The following headers are set in the file handler:

[0] "Server"    "Microsoft-IIS/7.5"
[1] "Set-Cookie"    "lang=nl; expires=Tue, 04-Feb-2014 13:08:56 GMT; path=/"

And the Expires property of the Response object is:

context.Response.Expires = 0
like image 867
ThdK Avatar asked Jan 24 '13 15:01

ThdK


2 Answers

I believe the root issue is that Chrome isn't caching the image. In this demo, Chrome will issue a new request every time you click the button.

The lazy load script triggers 2 requests because it first (pre)loads the image into a private img element, then it assigns the image URL to the original img element.

I suggest adding an Expires or Cache-Control header, and a Last-Modified or ETag header, to the response from your image handler so that Chrome will cache the image. (For more on caching, see the Caching Tutorial for Web Authors and Webmasters.)


Update: I suggest adding something like this to your image handler (from MSDN):

Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
like image 102
Jeffery To Avatar answered Oct 03 '22 08:10

Jeffery To


When something like this happens, make sure you don't have Chrome DevTools opened and "Disable cache" checkbox ticked. If any addon, setting or anything else causes cache to be disabled, same thing might happen.

like image 45
Mark Avatar answered Oct 03 '22 08:10

Mark