Auto click a Button when script/page loaded

I’m trying to a little script that would click a button when the page is loaded or even better when the script XYZ.js is loaded.

The script I have done works, but only if I add a delay to it. Which is a bit confusing because it normally should also work without adding a delay.

WORKS

window.addEventListener("load", function() {
    setTimeout(function() {
    var button = document.querySelector(".myJS-Button");
        if (button) {
            button.click();
        }
    }, 1);
});

DOESN’T WORK

window.addEventListener("load", function() {
    var button = document.querySelector(".myJS-Button");
    if (button) {
        button.click();
    }
});