Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript Event Listener Inline vs. Explicit

I am using Tampermonkey for some webpage manipulation and automation. For this, I add an event listener to the window "load" event. When I define the event handler as an explicit function, it works smoothly and as expected, i.e. the function is called whenever the relevant page is loaded.

window.addEventListener("load", run());

function run() {
    // do something
}

However, when I define the handler inline as follows

window.addEventListener("load", function (){
     // do something
});

then I need to refresh / reload the page several times before the function gets executed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is the explanation to have such very different behaviour? I would have expected no difference whether I define the function "explicitly" as in the first example, or "inline" as in the second one. As I have not noticed this before I don’t even know whether this is a Tampermonkey issue or a Javascript one.

>Solution :

window.addEventListener("load", run()); does not run the run function on load but immeditaly and the value returned by run is then used as callback (which is likely undefined). This is a duplicate to addEventListener calls the function without me even asking it to

About the:

then I need to refresh / reload the page several times before the function gets executed.

You then likely register the event listener to late (at a point when the page was possibly already loaded).

I don’t even know whether this is a Tampermonkey issue or a Javascript one.

It is none of these, it is a false assumption from your side that the site cannot be already loaded at the time you register the load event.

You like want to have something similar to the ready function of jQuery which an example implementation without jQuery can be found here $(document).ready equivalent without jQuery.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading