按顺序加载图像

我正在构建一个包含大量大图像(10-40,~300kb / img)的网站,并寻找一种顺序加载(不显示!)的方式。

我已经有一块js,一旦前3个图像被加载就会显示并触发旋转木马(其他的将在前3个显示时加载到背景上),因为图像将异步加载,它没有多大用处。

这样,有没有一种方法只在加载前一个图像时加载图像?

这是我的HTML。

我的js:

 var numImagesLoaded = 0; function incrementAndCheckLoading(){ numImagesLoaded++; if(numImagesLoaded == 4){ // trigger carousel } } image1 = new Image(); image1.src = "http://cccctanger.com/test/img/1.jpg" image1.onload = incrementAndCheckLoading; image2 = new Image(); image2.src = "http://cccctanger.com/test/img/2.jpg" image2.onload = incrementAndCheckLoading; image3 = new Image(); image3.src = "http://cccctanger.com/test/img/3.jpg" image3.onload = incrementAndCheckLoading; image4 = new Image(); image4.src = "http://cccctanger.com/test/img/status.gif" image4.onload = incrementAndCheckLoading; 

编辑:旋转木马是基于bootstrap!

编辑2和解决方案

我已经改编了Luis Lorenzo的解决方案,将每个img附加到旋转木马上。 唯一的问题是:图像不会按顺序附加(1-2-3-4 -…),但是它们被加载。 考虑到这是一个我可以忍受的小问题,问题解决了:)))

多谢你们!!

这是js:

 $(document).ready(function () { var images = ["http://cccctanger.com/test/img/1.jpg", "http://cccctanger.com/test/img/2.jpg", "http://cccctanger.com/test/img/3.jpg", "http://cccctanger.com/test/img/4.jpg", "http://cccctanger.com/test/img/5.jpg"]; var numImagesLoaded = 0; $.each(images, function(k, v) { image_temp = new Image(); image_temp.src = v; image_temp.onload = function () { $('#carousel-inner').append('
'); numImagesLoaded++; if(numImagesLoaded == 4) { $('#status').fadeOut(); // will first fade out the loading animation $('#preloader').delay(350).fadeOut('slow', function(){ $( "#carousel-example-generic" ).attr('data-ride', "carousel"); $( ".item" ).first().addClass( "active" ); }); // will fade out the white DIV that covers the website. $('body').delay(350).css({'overflow':'visible'}); $('.carousel').carousel({ pause: "false", interval: 10000 }); $('.carousel').css({'margin': 0, 'width': $(window).outerWidth(), 'height': $(window).outerHeight()}); $(window).on('resize', function() { $('.carousel').css({'width': $(window).outerWidth(), 'height': $(window).outerHeight()}); }); } } }); });

和相关的HTML:

 

尝试使用javascript加载图片,并在完成后附加到html。 像这样的东西:

HTML

  

JS(使用jQuery)

 $(document).ready(function () { var images = ["http://cccctanger.com/test/img/1.jpg", "http://cccctanger.com/test/img/2.jpg", "http://cccctanger.com/test/img/3.jpg", "http://cccctanger.com/test/img/4.jpg"]; var numImagesLoaded = 0; $.each(images, function(k, v) { image_temp = new Image(); image_temp.src = v; image_temp.onload = function () { $('#carousel').append('
'); numImagesLoaded++; if(numImagesLoaded == 4) { //carousel } } }); });

示例: http : //jsfiddle.net/hD3Sc/