TheColonel26
TheColonel26

Reputation: 2728

how can I asynchronously load an image on page load and display a loading gif while it loads?

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..." />

Upvotes: 0

Views: 1082

Answers (1)

adeneo
adeneo

Reputation: 318182

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();
});

Upvotes: 3

Related Questions