'How can I run code in the onload event in a file and in a script tag

I wish to add code to a click event in a file and a script tag. But they seem to conflict. How can I achieve this?

javascript:

 window.onload = function()
 {
     document.getElementById("button3").addEventListener("click", respond3);
 }

 function respond3(e)
 {
     alert("Way to go!!");
 }

html:

<head>
    <title>Second Javascript</title>

    <script src="Second.js"></script>
    <script>
        window.onload = function()
        {
            document.getElementById("button2").addEventListener("click", respond);
        }

        function respond(e)
        {
            alert("getting better");
        }
    </script>

</head>

<body>
    <h1>The quick brown fox jumps over the lazy dogs</h1>
    <button onclick='alert("bad practice");'>Inline</button>
    <button id='button2'>Script tag</button>
    <button id='button3'>Separate file</button>
</body>

Per Quentin's suggestion I changed the script tag to this:

<script>
    window.addEventListener('load', AddClick2)

    function AddClick2()
    {
        document.getElementById("button2").addEventListener("click", respond);
    }

    function respond(e)
    {
        alert("getting better");
    }

</script>


Solution 1:[1]

The on* properties can only have one function assigned to them. It's not so much a conflict as you are simply overwriting the first onload function with the second.

While you could do something along the lines of checking to see if there is already a function there, then copying it to a new variable, then calling it from the new variable inside your new onload function … that gets messy.

Use addEventListener instead.

window.addEventListener('load', a_function);
window.addEventListener('load', a_different_function);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin