0

Here is my image tag. The image is graph that is generated dynamically from the database. The amount of data involved can vary by a lot. Sometimes it loads in less than a second and other times it can be up to 6 or 7 seconds until the graph image is returned and displayed. What I want to do is display a simple place holder gif until that actual image in loaded.

<img src="@Url.Action("Graph", new { id =  Model.ID })" alt="Graph is Loading..." />
TheColonel26
  • 2,618
  • 7
  • 25
  • 50
  • possible duplicate http://stackoverflow.com/questions/15826158/how-to-load-gif-image-while-ajax-content-is-loading-and-javascript?rq=1 – Alex Nov 14 '13 at 16:59
  • http://stackoverflow.com/questions/16810423/show-spinning-wheel-image-till-the-full-page-loads?rq=1 – Alex Nov 14 '13 at 16:59
  • Point the src at the placeholder and include the url to the graph in a data attribute. Next, on document ready, create a new hidden image, give it a load handler that hides the placeholder and shows itself, then set the src of the image to the graph. – Kevin B Nov 14 '13 at 17:00

1 Answers1

3

Disregarding your ASP completely, you can add the element with the loader as the source and the real image as a data attribute, then load the image with javascript, and swap images once the real image has loaded:

<img src="loader.gif" data-src="/images/menubar.png" />

JS preloading

$('img').each(function() {
    var self = this,
        src  = $(self).data('src'), // get the data attribute
        img  = new Image();         // create a new image

    img.onload = function() {       // onload
        self.src = this.src;        // swap the source
    }

    img.src = src;                  // set source of new image

    if (this.complete) $(this).load();
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • wouldn't this depend on the server sending proper caching headers with the image? if it's a dynamically generated image i'd expect the src swap to cause the database to have to re-generate it unless the server is setup to cache the result. – Kevin B Nov 14 '13 at 17:04
  • @KevinB - Yes, proper caching would have to be enabled, otherwise it will just generate the image again, and the preloading wouldn't really do much good. In my opinion the serverside should be made to send out proper headers if that is an issue, but a hack could be to use two image tags, and toggle the visibility on image onload, but a hidden image doesn't load in most browsers, so that solution would probably require a lot of hacks to get working. – adeneo Nov 14 '13 at 17:09
  • Can you tell me how to do that with a single image? That runs on all images on the page right? – TheColonel26 Nov 14 '13 at 17:34
  • Just change the selector from `$('img')` to `$('#ID_of_my_image')` – adeneo Nov 14 '13 at 17:45