如何在页面加载时异步加载图像并在加载时显示加载 GIF

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

本文关键字:加载 显示 GIF 图像 异步      更新时间:2023-09-26

这是我的图像标签。图像是从数据库动态生成的图形。所涉及的数据量可能会有很大差异。有时它会在不到一秒的时间内加载,有时最多可能需要 6 或 7 秒,直到返回并显示图形图像。我想做的是显示一个简单的占位符 gif,直到加载实际图像。

<img src="@Url.Action("Graph", new { id =  Model.ID })" alt="Graph is Loading..." />

完全忽略您的 ASP,您可以添加将加载器作为源的元素,将真实图像作为数据属性,然后使用 javascript 加载图像,并在加载真实图像后交换图像:

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

JS预加载

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