获取未加载的元素

Get elements that did not load

本文关键字:元素 加载 获取      更新时间:2023-09-26

如何找出由于找不到资源而未加载的所有元素?

    <body>
       <img src="notThere.png">
       <script src="notInHere.png"></script>
       <img src="DoesExist.png">
       // want to find the first and the script with unexisting sources, but not the second image with an existing source.
    </body>

有人能给我一个如何找出这些元素的提示吗?我认为,为每个元素设置onerror不是解决方案,因为元素可能是动态加载的。。

不幸的是,window.onerror没有在"找不到资源"错误中激发。

示例:

    <body>
        <script src="someonesScript.js"></script> <!-- this script might load images/audio etc.. -->
        <script>
           // now put here whatever you like
           // but find out which resources (images,scripts,..) were tried to load (from the script above)
           // and can't be loaded    
        </script>
    </body>

希望这个例子能帮助理解我的问题。

虽然理论上error事件和冒泡(error事件应该冒泡)是可能的,但遗憾的是,浏览器对它的支持很弱(至少可以说)

充其量,您可以在特定时刻循环遍历DOM,查找所有src属性,并检查它们是否指向有效的资源(通过其他人建议的方法)。但这不会抓住任何被移除的东西。

来源:

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-事件分组事件

http://www.quirksmode.org/dom/events/error.html

您可以使用JavaScript方法onerror来检查:

<img src="false.jpg" onerror="alert('Failed to load');" />

但是,如果动态加载图像,则可以使用file_exists()等函数。

function ImageExist(url) 
{
   var img = new Image();
   img.src = url;
   return img.height != 0;
}

我从用户cichy上找到了这个:如何检查文件是否存在于jQuery或JavaScript中?

使用此函数,只需执行以下操作:如果不存在(onload),则将图像名称添加到数组中。在那里,你将拥有的所有信息

编辑:

若您想在页面上找到所有图像,请尝试PHP Simple HTML DOM Parser。你必须先在这里下载。一个例子(在NAVEED关于如何在PHP中解析和处理HTML/XML的帖子的帮助下创建的):

<?php
$html = file_get_html('filename.php');
$image_names = array(); //store all image_names in here 
foreach($html->find('img') as $element){
$image_names[] = $element->src;
}
function check_images($array){
foreach($array as $img){
    if(@getimagesize($img)) echo "true"; else echo "false: ".$img;
}
}
check_images($image_names);

如果对我来说效果很好!