简体   繁体   中英

loading large background images eliminating white space while waiting for load

below is the javascript that I am currently experimenting with. I am teaching myself JS. As things stand this code begins with white space instead of the first image. I wanted to ask somebody if the bgcur=0 would give me a background image at the beginning, instead of white space until the first image loads, which is what currently happens.

If not could somebody show me how to build a preloader for these images?

<script type="text/javascript">
var bgArr = [
 'images/bg1.jpg',
'images/bg2.jpg',
'images/bg3.jpg',
'images/bg4.jpg',
'images/bg5.jpg',
'images/bg6.jpg',
'images/bg7.jpg',
'images/bg8.jpg',
'images/bg9.jpg',
'images/bg10.jpg'];

document.body.style.backgroundImage = 'url(' + bgArr[10] + ')';
bgCur = 0;
backgroundSwitch = function () {
if (bgCur == bgArr.length) bgCur = 0;
document.body.style.backgroundImage = 'url(' + bgArr[bgCur++] + ')';
}
window.setInterval(backgroundSwitch, 6000); // Switch every 6 seconds.
</script>

No point putting the background image to the index 10 of your array when it doesn't exist. Start with

document.body.style.backgroundImage = 'url(' + bgArr[9] + ')'; //any value between 0-[arraylength-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM