简体   繁体   English

只加载一次脚本

[英]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.但这不起作用,因为load总是被加载。 How would I approach that?我将如何处理?

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.最初localStorage.getItem("beenHere")是 null 因此它的计算结果为 false,因此 if 条件中的代码永远不会运行并且beenHere永远不会设置为 1。

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

Add { once: true } as a third option for addEventListener添加{ once: true }作为 addEventListener 的第三个选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM