使用jquery预加载图像

在我的网页中,一些图像需要花费大量时间才能在IE中加载。所以我用这个来预加载我的页面中的图像。但问题仍然存在。任何建议?

function preload(arrayOfImages) { $(arrayOfImages).each(function(){ $('')[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>

 // Create an image element var image1 = $('').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 $('') .attr('src', 'imageURL.jpg') .load(function(){ $('.profile').append( $(this) ); // Your other custom code }); 

更新#1

 function preload(arrayOfImages) { $(arrayOfImages).each(function(index){ $('') .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插件: 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 }); 

图像精灵可以极大地提高速度(但请确保使用ImageOptim之类的东西压缩它们)。 接下来,将您的所有图像托管在某个CDN上(我建议使用Amazon S3 / CloudFront)。 最后,使用下面的内容预加载所有图像,并尝试尽早调用它。 希望这有帮助!

 function loadImages(){ var images = [ 'http://sofzh.miximages.com/jquery/image1.png', 'http://sofzh.miximages.com/jquery/image2.jpg', 'http://sofzh.miximages.com/jquery/image3.jpg', 'http://sofzh.miximages.com/jquery/image4.jpg' ]; $(images).each(function() { var image = $('').attr('src', this); }); }