- . loadImages
, . .then
cycleImages
, . URL- JS, , background-image
, URL- CSS . , , if.
function loadImages (images) {
let loader = function (src) {
return new Promise(function (resolve, reject) {
let img = new Image();
img.onload = function () {
resolve(src);
};
img.onerror = function (err) {
reject(err);
};
img.src = src;
});
};
let loaders = [];
images.forEach(function (image) {
loaders.push(loader(image));
});
return Promise.all(loaders);
}
let myImages = [
'http://www.gifpng.com/400x200',
'http://www.gifpng.com/400x200/ffffff/000000',
'http://www.gifpng.com/400x200/000000/ffffff'
];
$(function() {
function cycleImages (images) {
let index = 0;
setInterval(function() {
$('#backgrounds').css('backgroundImage', 'url("' + images[index] + '")');
index = (index + 1) % images.length;
}, 750);
}
loadImages(myImages).then(cycleImages).catch(function (err) {
console.error(err);
});
});
#backgrounds {
height: 200px;
width: 400px;
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="backgrounds"></div>
Hide resultEdit:
, , , , . , . cycleImages
.then
, , ( jQuery) promises. , , .
function loadImages (images) {
let loader = function (src) {
return new Promise(function (resolve, reject) {
let img = new Image();
img.onload = function () {
resolve(src);
};
img.onerror = function (err) {
reject(err);
};
img.src = src;
});
};
return images.map(function (image) {
return loader(image);
});
}
let myImages = [
'http://www.gifpng.com/400x200',
'http://www.invalid-domain-name.foo/this-url-certainly-does-not-exist.jpg',
'http://www.gifpng.com/400x200/ffffff/000000',
'http://www.gifpng.com/400x200/000000/ffffff'
];
$(function() {
function cycleImages ($target, images) {
let index = 0,
interval = 750;
function nextImage () {
let p = images[index],
next = function (wait) {
index = (index + 1) % images.length;
setTimeout(nextImage, wait);
};
p.then(function (src) {
$target.css('backgroundImage', 'url("' + src + '")');
next(interval);
}).catch(function (err) {
next(0);
});
}
nextImage();
}
cycleImages($('#backgrounds'), loadImages(myImages));
});
#backgrounds {
height: 200px;
width: 400px;
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="backgrounds"></div>
Hide result. , , : cycleImages(myImages, {target: $('#backgrounds'), interval: 1000});