在 Javascript 中验证来自 API 的图像 URL



我从API获得一个图像URL数组,但其中一些已损坏。在将它们附加到DOM之前,有没有一种方法可以验证它们以检查它们是否已损坏?

???

function imgURL_checker (obj_URL_ChildNode_Arr)
{
var iterator=0, l=obj_URL_ChildNode_Arr.length,
img=document.createElement ("img");
function load ()
{
obj_URL_ChildNode_Arr[iterator].childNode.appendChild (img.cloneNode ());
iterator++;
next ();
}
function error ()
{
console.log ("URL not found: "+img.src);
iterator++; 
next ();
}
function next ()
{
if (iterator<l) img.src=obj_URL_ChildNode_Arr[iterator].url;
else
{
console.log ("finished");
//-- destroy
img.removeEventListener ("load" ,load);
img.removeEventListener ("error",error);
img=null;
}
}
img.addEventListener ("load",load);
img.addEventListener ("error",error);
next ();
}
imgURL_checker ([{url:"https://cdn.pixabay.com/photo/2014/04/02/10/42/kitties-304268__340.png",childNode:document.body},{url:"http://___",childNode:document.body},{url:"https://cdn.pixabay.com/photo/2014/12/21/23/58/fox-576494__340.png",childNode:document.body}]);

最新更新