如何监听net :: ERR_FILE_NOT_FOUND错误

时间:2017-08-12 19:13:50

标签: javascript

我试图在浏览器未加载css文件或js文件时发现错误

我正在寻找的是这样的

<html>
  <head>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1 id="#status">Status : ...</h1>
  </body>

  <script>
    docuement.whenLoadErrorHappen = function () 
    {
        document.findElementById("status").innerHTML = "Error Loading File";
    }
  </script>

</html>

2 个答案:

答案 0 :(得分:1)

使用附加到error和/ <link>元素的<script>事件,请参阅Is there a way to know if a link/script is still pending or has it failed

答案 1 :(得分:0)

要检查是否存在css文件,只需检查是否存在<link>元素,并将href属性设置为您的CSS文件的网址:

  if (!$("link[href='/path/to.css']").length){
      // css file not exist
  }

js

if (!$("script[src='/path/to.js']").length){
     // js file not exist
}