2017-07-17 93 views
0

我试图预加载20张图片。我写了这段代码,但我不确定它的工作原理。即使它们没有像素化,它们通过闪烁和滞后显得很奇怪。任何想法我做错了什么?预加载大量图像,停止预加载屏幕

$(window).on("load", (function() { 
    PrepareImgs(); 
    console.debug('loaded'); 
})); 
var sectionArray = ["whoAreWe", "video", "web", "community", "charity"]; 
var imgArray = []; 
function PrepareImgs() { 
// console.debug("PrepareImgs started"); 
for (var i = 0; i < 5; i++) { 
    for (var j = 1; j <= 4; j++) { 
     var zdj = "Assets/Images/CroppedAndCleaned/" + sectionArray[i] + "/pp" + j + ".jpg"; 
     imgArray.push(zdj); 
    } 
} 
LoadImages(); 
} 

function LoadImages() { 
// console.debug("LoadImages started"); 
var i = 0; 
$(imgArray).each(function() { 
    // console.debug("loop started"); 
    var img = new Image(); 
    $(img).attr('src', imgArray[i]); 
    img.src=imgArray[i]; 
    console.debug(i); 
    // function preloadImage(url) 
    // { 
    //  var img=new Image(); 
    //  img.src=url; 
    // } 
    img.onload = function() { 
     console.debug("Internal loop started"); 
     i+=1; 

     if (i == $(imgArray).length) 
      HideLoader(); 
    } 
}); 
} 
function HideLoader() { 
// console.debug("HideLoader Started"); 
setTimeout(function() { 
    $('body').addClass('loaded'); 
}, 1); 
} 
+0

我认为主要的问题就在于你的'onload'处理程序中。两个显而易见的问题是'onload'是异步的;每个图像的加载事件将在不同的时间触发,具体取决于加载需要多长时间,并且可能不按照您期望的顺序。 “i”的增量可能不会影响外部范围中的“i”。此外,您不需要将'imgArray'传递给'jQuery()'以获得长度。因为它可能会返回'0'或'1'而不是'20'。 –

+0

是的,它总是返回0,这是令人困惑的。所以我应该停止循环,直到事件onload完成?它甚至有可能吗? – alex3wielki

回答

0

尝试以此为榜样, 它加载图像,并将它们一次追加到DOM所有的人都加载。

它使用Promises

function preloadImages(...images) { 
 

 
    return Promise 
 
    .all(
 
     images.map((src, i) => new Promise((resolve, reject) => { 
 
     src = `https://lorempixel.com/400/200/${src}/Image-Number-${i}`; 
 
     const img = $('<img />'); 
 

 
     return img 
 
      .attr('src', src) 
 
      .on('load',() => resolve(img)) 
 
      .on('error', reject) 
 
     })) 
 
    ) 
 
    ; 
 
}; 
 

 

 
preloadImages('sports', 'food', 'business', 'animals', 'nightlife', 'fashion') 
 
    .then(res => { 
 
    console.log('images loaded'); 
 
    
 
    return res.forEach($img => $img.appendTo('body')) 
 
    }) 
 
;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

您可以解释.then(res => part? – alex3wielki

+0

['Promise.prototype.then'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/)然后)接受一个回调函数,当promise被解析时,这个回调函数会被调用。 – Hitmands

+0

它就像是一个伪代码吗?我的IDE在使用=> – alex3wielki