2010-12-22 93 views
5

在我的网页中,一些图像需要花费大量的时间在IE中加载。因此,我用它来预加载图像到我的页面中,但问题仍然存在。有什么建议吗?使用jquery预加载图像

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>

+0

您是否正在使用javascript预装图像以查找特定原因? – 2010-12-22 06:52:49

回答

8
// 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事件。

// 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' 
]); 
2

试试这个jQuery插件:http://farinspace.com/jquery-image-preload-plugin/

它允许您使用选择抢img元素并将它预载他们。我不知道,如果你想预载的图片已经在HTML,如果他们是因为它可以让你做你可能有兴趣通过这个插件:

$('#content img').imgpreload(function() 
{ 
    // this = jQuery image object selection 
    // callback executes when all images are loaded 
}); 

,同时还允许你手动预先载入图像与文件名:

$.imgpreload('/images/a.gif',function() 
{ 
    // this = new image object 
    // callback 
}); 
0

图片精灵可以极大地加快速度(但要确保你使用类似ImageOptim压缩它们)。接下来,将所有图像托管在某个CDN上(我建议使用Amazon S3/CloudFront)。最后,使用类似于下面的内容预载所有图像,并尽可能早地调用它。希望这有助于!

function loadImages(){ 
    var images = [ 
     'http://cdn.yourdomain.com/img/image1.png', 
     'http://cdn.yourdomain.com/img/image2.jpg', 
     'http://cdn.yourdomain.com/img/image3.jpg', 
     'http://cdn.yourdomain.com/img/image4.jpg' 
    ]; 
    $(images).each(function() { 
     var image = $('<img />').attr('src', this); 
    }); 
}