【问题标题】:how to listen for net::ERR_FILE_NOT_FOUND error如何监听 net::ERR_FILE_NOT_FOUND 错误
【发布时间】:2017-08-12 19:13:49
【问题描述】:

当浏览器未加载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>

【问题讨论】:

  • 也许可以试试 try-catch 块。有点像here

标签: javascript


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    要检查css 文件是否存在,只需检查&lt;link&gt; 元素是否存在并将href 属性设置为您的CSS 文件的URL:

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

    对于js

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

    【讨论】:

    • Answer 的方法如何实际检查文件请求是否成功?
    猜你喜欢
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多