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

时间:2012-07-25 00:56:05

标签: jquery preload

这些图像是动态加载的:

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

此刻无法运行动态脚本,因此图像标记当前是静态的。这段代码看起来好像应该有效还是我遗漏了什么?

1 个答案:

答案 0 :(得分:2)

我根据我的初步评论的想法制作了一个快速片段,这应该适用于跨域:

$(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