我编写了一个图片库。任何图像上的 onclick
事件都会在模态窗口中加载图像。当前,仅通过替换 img
标记的 src
属性的值来加载图像。
我的问题是:我可以使用 ajax 加载图像吗?这样做会以任何方式提高性能(即最小化加载时间)吗?
我的下一个问题是:我想在浏览器等待通过单击模态窗口的下一步按钮加载新图像时使用微调器。我不知道该怎么做。任何建议都会有所帮助。
这是我的图库的 jsfiddle jsFiddle
我用来加载图像的 jquery 代码:
$('.gallery a').click(function(evt) {
var imgPath = $(this).attr('href');
$('.gallery-overlay').find('.gallery-image').attr('src',imgPath);
});
最佳答案
先回答下一个
问题。
如果您一次加载图像。
如果你使用 ajax,这个函数应该被实例化以加载图像,这将显示 ajax-spinner 直到图像被加载。
jQuery
//Assuming gallery-overlay is id of the div where you are showing image.
$(function(){
$("#gallery-overlay").html("<img src='ajax-spinner.gif'>");
$.post(url,{variable:variable},function(data){
$("#gallery-overlay").html(data);
//data is whatever your php file returns. The ajax-spinner will be there till this appends the html returned by your php file.
});
})
PHP
//Post variables
//Get the src and image details from table.
$src = $row['src-in-db'];
$alt = $row['alt-in-db'];
$width = $row['width-in-db'];
$height = $row['height-in-db'];
//Echo the html code for #gallery-overlay.
echo "
<img src='".$src."' width='".$width."' height='".$height."' alt='".$alt."'>
";
然后对于下一个和上一个按钮,您将不需要您在 fiddle 中完成的 jQuery。您将需要另一个 php 文件来向您发送图像 html。
第一个问题的答案
正如我在您之前的问题中所说,IMO,这将取决于您一次加载多少图像。告诉我你加载了多少?
您还完成了 jQuery 的全部工作,所以我建议暂时不要使用 ajax。如果您还要加载大约 20-25 张图片。
这里有一些你必须要看的问题。
Question 2 .(这些答案足以解决您的第一个问题)
因为这是一个图片库,所以我确信您会在模态窗口外的预览中显示图像,对吧?
那么就完全没有必要使用ajax了,因为图片已经被浏览器缓存了。
结论:不要使用 ajax。让它成为你已经做过的事情。只需为 esc 按钮添加关闭按钮或事件处理程序即可关闭模态窗口。
增加浏览器对 img 缓存的 max-age,
How do you cache an image in Javascript
Google link
关于javascript - 在图片库中使用 ajax 加载图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17902121/