gpt4 book ai didi

jquery - 使用 jquery 预加载动态加载的图像

转载 作者:行者123 更新时间:2023-12-01 04:19:53 25 4
gpt4 key购买 nike

这些图像是动态加载的:

<div id="gallery-images" class="gallery-control">
<ul>
<img class="galleryImgs" data-src="images/test-image-1.jpg" src="images/test-image-1-s.jpg" />
<img class="galleryImgs" data-src="images/test-image-2.jpg" src="images/test-image-2-s.jpg" />
<img class="galleryImgs" data-src="images/test-image-3.jpg" src="images/test-image-3-s.jpg" />
</ul>
</div>

我正在尝试从每个 img 标签的“data-src”属性中预加载图像 URL。这是我写的代码:

$('.galleryImgs').each(function(){
$('<img/>')[0].src = $(this).attr("data-src");
});

目前无法运行动态脚本,因此图像标签当前是静态的。这段代码看起来应该可以工作还是我遗漏了什么?

最佳答案

我用我最初的评论的想法制作了一个快速片段,它应该可以跨域工作或不工作:

$(function() {
//creates an imgcacher hidden element
$('<div/>', {id: 'imgcacher', style: 'display:none;'}).appendTo('body');
var cacher = $('#imgcacher'); //caches the cacher selector

//appends the images to the DOM for caching
$('.galleryImgs').each(function(){
$('<img/>', {src: $(this).data('src'), class: "precachedImg"}).appendTo(cacher);
});

//clean up the DOM after the images are fully loaded and cached
$('.precachedImg').promise().done(function() {
cacher.remove();
});
});​

DEMO
请注意,如果您的连接速度不够快,第二张图片可能会稍微太大而无法在 5 秒内加载,但此时它至少应该部分加载。

当我测试它时,

$.get 无法在 Chrome 上缓存图像,因此上面的解决方案是我的首选。它在我测试过的所有浏览器上以任何连接速度和文件大小都能很好地工作。现代浏览器只会请求一次图像资源,并将其与页面中的所有其他重复内容并行显示,而不会像 ajax 请求那样生成额外的请求。

此外,它还是一个动态、可扩展且干净的解决方案。如果您更喜欢简单性,那么它与最初将带有 display:none 的图像添加到 DOM 相比,具有“相同”的最终用户体验。显然,这会不必要地扰乱 DOM,因此我将使用上面的代码片段。

此外,这是一个稍微简化的版本:

$(function() {
//appends the images to the DOM for caching
$('.galleryImgs').each(function(){
$('<img/>', {src: $(this).data('src'), class: 'precachedImg', style: 'display:none;'}).appendTo('body');
});

//clean up the DOM as the images are loaded and cached
$('.precachedImg').load(function() {
$(this).remove();
});
});

Fiddle

关于jquery - 使用 jquery 预加载动态加载的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com