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

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?

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

>Solution :

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")) {
    ...
}
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