Search code examples
javascriptonerror

Call script tag onerror manually from external script


I have the following script tag of an external (but self controlled javascript file):

<script async 
    src="//domain/test.js" 
    onerror="
        (function() {
            doSomething(); 
        })(); 
    ">
</script>

The script is not critical and a good fallback exists. I want to trigger my fallback:

  • If test.js is unavailable (This works)
  • In test.js code manually.

Is there a way to trigger the onerror event of a script tag in the script itself? Or is there another solution to solve this without repeating the onerror code?


Solution

  • If you can modify the script tag at all then it's easy. Give it an id and you can select it by that id and trigger anything attached to it. Here's an example...

    document.querySelector("#script-tag").onerror();
    <script id="script-tag" onerror="(function() { alert('error!!!'); })()"></script>

    If you can't modify the script tag then you could identify it by the very fact it has an onerror attribute...

    document.querySelector("script[onerror]").onerror();
    

    If you have more than one script with an onerror attribute then you can get all the scripts and parse them manually, looking for the filename.

    document.querySelectorAll("script").forEach(function(script) {
        if (script.indexOf("test.js") != -1) {
            script.onerror();
        }
    });