如何找出所有因为未找到资源而未加载的元素?
<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-eventgroupings-htmlevents
关于javascript - 获取未加载的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18155696/