3

这些图像是动态加载的:

<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");
});

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

4

1 回答 1

3

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

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

演示
请注意,如果您的连接速度不够快,第二张图像可能会稍大,无法在 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();
    });
});

小提琴

于 2012-07-25T02:54:08.370 回答