使用jQuery预加载图像 [英] Preload images using jquery

查看:89
本文介绍了使用jQuery预加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网页中,某些图像需要花费很多时间才能在IE中加载.所以我用它来预加载页面中的图像,但是问题仍然存在.有什么建议吗?

In my web page some images are taking a lot of time to load in IE.So I used this for preloading images in my page.But still the problem persists.Any suggestions?

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    });
    alert("Done Preloading...");
}

// Usage:

preload([
    '/images/UI_1.gif',
    '/images/UI_2.gif',
    '/images/UI_3.gif',
    '/images/UI_4.gif',
    '/images/UI_5gif',
    '/images/UI_6.gif',
    '/images/UI_7.gif',
    '/images/UI_8.gif',
    '/images/UI_9.gif'
]);

<

div>

div>

推荐答案

// Create an image element
var image1 = $('<img />').attr('src', 'imageURL.jpg');

// Insert preloaded image into the DOM tree
$('.profile').append(image1);
// OR
image1.appendTo('.profile');

但是最好的方法是使用回调函数,因此它将在完成加载后将预加载的图像插入应用程序.为此,只需使用.load()jQuery事件.

But the best way is to use a callback function, so it inserts the preloaded image into the application when it has completed loading. To achieve this simply use .load() jQuery event.

// Insert preloaded image after it finishes loading
$('<img />')
    .attr('src', 'imageURL.jpg')
    .load(function(){
        $('.profile').append( $(this) );
        // Your other custom code
    });

更新#1

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(index){
        $('<img />')
        .attr('src', arrayOfImages[index])
        .load(function(){
            $('div').append( $(this) );
            // Your other custom code
        });
    });
    alert("Done Preloading...");
}

// Usage:

preload([
    '/images/UI_1.gif',
    '/images/UI_2.gif',
    '/images/UI_3.gif',
    '/images/UI_4.gif',
    '/images/UI_5gif',
    '/images/UI_6.gif',
    '/images/UI_7.gif',
    '/images/UI_8.gif',
    '/images/UI_9.gif'
]);

这篇关于使用jQuery预加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆