【问题标题】:window.onerror: url property empty when error in dynamically added script (via script tag)window.onerror:动态添加的脚本中出现错误时 url 属性为空(通过脚本标签)
【发布时间】:2016-10-01 16:24:25
【问题描述】:

我希望能够知道动态添加的脚本中是否发生错误。这应该通过检查onerror 事件参数的url 属性来完成。

但是,当我在脚本开头添加事件侦听器时,即在动态添加脚本标记之前,如果动态添加的脚本内部发生错误,url 属性将为空。

所以我尝试在添加脚本标签后重新绑定事件

document.head.appendChild(scriptElement);
document.getElementById(scriptTagId).addEventListener('onerror',someErrorFunction);

还有

scriptElement.setAttribute('onerror','someErrorFunction(event);');
document.head.appendChild(scriptElement);

也喜欢

document.head.appendChild(scriptElement);
window.addEventListener('onerror',someErrorFunction);

但无济于事。实际上,错误甚至只是使用第一种方法被捕获,即在脚本开头绑定onerror 事件。

【问题讨论】:

    标签: javascript events dynamic onerror


    【解决方案1】:

    我认为您在通过 id 获取脚本元素时遇到了问题。您可以使用简单的脚本加载器来实现最终结果。主要区别在于它绑定到脚本元素的onerroronload 属性,而不是使用事件监听器

    编辑

    使用window.onerror 并绑定到onafterscriptexecute 而不是onload 并使用document.currentScript 获取引发错误的脚本标记,我对此脚本没有任何问题。

    window.onerror = function(message, source, lineno, colno, error){
      console.log('window.error', {
        message,
        source,
        lineno,
        colno,
        error,
        src: document.currentScript.src
      })
    }
    
    function loadScript(src, callback) {
      console.log('loading: ' + src)
      const script = document.createElement('script')
      script.onerror = function() {
        console.log('error loading script: ' + src)
      }
      script.onafterscriptexecute = callback
      script.src = src
      document.head.appendChild(script)
    }
    
    loadScript('http://codepen.io/synthet1c/pen/BLwWOb.js', function(){
      console.log('this aint gonna happen')
    })
    
    loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', function(){
      console.log('success loaded jQuery')
    })

    【讨论】:

    • 感谢您的回答。不幸的是,这仅在脚本文件的 url 错误时才有效;但是,它不考虑脚本本身的语法错误或一般异常。
    • 我需要的是document.currentScript。不知道这存在,再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多