javascripthtmlonerror

Is there a way to call a external script with an event


I'm working on a script, and I'm wondering, can I call a External script, such as <script src='example.com'></script> but with an event, so onload='[run external script]' with a one-liner? This is what I'm currently working on

<img src='/HelloWorld' onerror='[run code on external web]'></img>

I'm working with a longer script, and I don't want to use event listeners. and I would prefer little, to no other code.

edit I dont know what i should try out.


Solution

  • Well, yes. When you do <script src='example.com'></script>, that runs all the code in the script. So, if that file contains a function, that function is available to your page as if the function had been defined locally.

    So, given file http://example.com/myfile.js containing:

    function myerror()
    {
        alert("Error occurred!");
    }
    

    You can write:

    <script src="http://example.com/myfile.js"></script>
    ...
    <img src='HellowWorld', onerror='myerror();'>