我有一組需要添加到檔案中的影像 url(如下所示)。有些網址不包含圖片。我該如何檢查?
picUrls = ["https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/048.jpg","https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18166-shivling-whatsapp-image-and-dp.jpg","http://www.fakeurl.io/fakeimage1.jpeg","https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18416-navratri-image-for-whatsapp-and-facebook.jpg"]
我正在使用 jquery 并嘗試過 .load & .error
for(let i = 0; i < picUrls.length; i ) {
const picUrl = picUrls[i];
//create image to preload:
var imgPreload = new Image();
$(imgPreload).attr({
src: picUrl
});
//check if the image is already loaded (cached):
if (imgPreload.complete || imgPreload.readyState === 4) {
//image loaded:
//your code here to insert image into page
$('#content-container').append(imgPreload);
} else {
//go fetch the image:
$(imgPreload).load(function (response, status, xhr) {
if (status == 'error') {
//image could not be loaded:
console.log('error');
} else {
//image loaded:
//your code here to insert image into page
$('#content-container').append(imgPreload);
}
});
uj5u.com熱心網友回復:
您可以創建一個幫助函式,該函式回傳一個影像是否是有效影像的承諾
const picUrls = [
'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/048.jpg',
'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18166-shivling-whatsapp-image-and-dp.jpg',
'http://www.fakeurl.io/fakeimage1.jpeg',
'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18416-navratri-image-for-whatsapp-and-facebook.jpg',
];
const getOnlyValidImage = src =>
new Promise((resolve, reject) => {
const img = new Image();
img.src = src;
img.onload = () => resolve(img);
img.onerror = () => resolve(null);
});
const preloadImages = async () => {
for (let i = 0; i < picUrls.length; i ) {
const picUrl = picUrls[i];
const image = await getOnlyValidImage(picUrl)
if (image) {
$('#content-container').append(image);
}
}
};
preloadImages();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406636.html
標籤:
