3

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

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

它一个接一个地加载每个图像,导致整个网站变慢(甚至崩溃)。

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

非常感谢!

4

4 回答 4

3

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

于 2012-12-18T16:20:46.263 回答
1

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

解决方法

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

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

于 2012-12-18T16:39:45.513 回答
1

My solution:

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;
    });
}

Example:

imageExists(url)
    .then(() => console.log("Image exists."))
    .catch(() => console.log("Image not exists."));
于 2018-02-27T20:36:02.967 回答
0

Here's how you can check if an image exists:

  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
}

Here's a working implementation http://jsfiddle.net/jeeah/

于 2013-05-02T06:44:22.723 回答