繁体   English   中英

检查图像是否存在而不加载它

[英]Check if image exists without loading it

我目前在悬停功能中使用以下脚本:

function UrlExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

它会逐个加载每个图像,导致整个网站速度变慢(甚至崩溃)。

有没有办法检查图像是否存在 ,但是使用javascript 阻止加载 (完全)?

非常感谢!

由于JavaScript(以及jQuery)是客户端的,并且图像在加载之前驻留在服务器端,因此无法在不使用Ajax或服务器端脚本的情况下检查图像是否存在以确保图像存在。

如果图像存在而没有加载它,则无法确定使用javascript或jQuery。

解决方法

检查服务器端是否存在图像的唯一方法是尝试将图像加载到隐藏的div或其他内容,然后检查图像是否存在然后显示它。

或者您可以使用您选择的某些服务器端语言(php,asp,jsp,python等)并将请求发送到服务器端语言(最好使用AJAX)并让服务器端脚本检查图像存在与否,如果存在则发回图像,如果不存在则发送错误代码。

以下是检查图像是否存在的方法:

  function checkImage(src) {
     var img = new Image();
     img.onload = function() {
     // code to set the src on success
  };
  img.onerror = function() {
// doesn't exist or error loading
 };

 img.src = src; // fires off loading of image
}

这是一个有效的实现http://jsfiddle.net/jeeah/

我的解决方案

function imageExists(url) {
    return new Promise((resolve, reject) => {
        const img = new Image(url);
        img.onerror = reject;
        img.onload = resolve;
        const timer = setInterval(() => {
            if (img.naturalWidth && img.naturalHeight) {
                img.src = ''; /* stop loading */
                clearInterval(timer);
                resolve();
            }
        }, 10);
        img.src = url;
    });
}

例:

imageExists(url)
    .then(() => console.log("Image exists."))
    .catch(() => console.log("Image not exists."));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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