KSPR
KSPR

Reputation: 2375

Load a script only once

I want to load a script only once when the user visits (a success page).

My idea was to write something with local storage:

if ( localStorage.getItem("beenHere")) {
    localStorage.setItem('beenHere', 1);
    window.addEventListener('load', (event) => {
        fathom.trackGoal('XXX', {{ order.totalPrice * 100 }});
    });
}

But that doesnt work because load is always loaded. How would I approach that?

Upvotes: 0

Views: 65

Answers (2)

Mikita Melnikau
Mikita Melnikau

Reputation: 1775

Add { once: true } as a third option for addEventListener

Upvotes: 0

Ivone Djaja
Ivone Djaja

Reputation: 753

It should be this instead? Initially localStorage.getItem("beenHere") is null so it evaluates to false, therefore the code inside the if condition never runs and beenHere is never set to 1.

if (!localStorage.getItem("beenHere")) {
    ...
}

Upvotes: 3

Related Questions