简体   繁体   English

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

[英]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. 有时,它在不到一秒钟的时间内加载,而在其他时候,它最多可能需要6或7秒才能返回并显示图形图像。 What I want to do is display a simple place holder gif until that actual image in loaded. 我要做的是显示一个简单的占位符gif,直到加载了实际图像为止。

<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: 完全不考虑您的ASP,您可以添加带有加载器作为源,将真实图像作为数据属性的元素,然后使用javascript加载图像,并在加载真实图像后交换图像:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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