问题
On the home page of my site I want to display a lot of products which have images which are quite large. Currently the page is taking so long to load that it is actually timing out and the page fails to display!
In MVC, or just ASP.NET in general, how can I load an image asynchronously? Basically what I want to do is display the details of the product and just display a small loading image e.g. ajaxload.info. until the image is loaded.
I assume this is going to require some javascript/jQuery...
回答1:
<img src="ajax-loader.gif" onload="this.onload=null;this.src='bigimage.png';" />
or if you prefer unobtrusively:
<img src="ajax-loader.gif" id="myimg" />
and then:
$(function() {
$('#myimg').load(function() {
$(this).unbind('load');
this.src = 'bigimage.png';
});
});
回答2:
First off, it's worth checking that the sizes of your images aren't humongous and simply scaled to dimensions appropriate for the page. In order for the loading time to be as best as it can be, the images ought to be the exact size you want to display them, 72dpi and no more. The images will most likely be cached after they are fetched the firs time so it should just be a one time cost.
I would be inclined to return only the url
to the image in your AJAX request. In fact, you wouldn't necessarily need to even make it an AJAX request. You could send out a JavaScript array of strings that have the urls
to the images in it then create a new Image
element (or similar) when the user hovers over a particular placeholder for the image.
Hopefully that's given you some ideas!
来源:https://stackoverflow.com/questions/3346739/asp-net-mvc-how-do-i-load-an-image-asynchronously