简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM