JavaScript事件函数在每个页面加载时运行一个

时间:2018-04-29 05:16:41

标签: javascript

我在页面的HTML body部分放置了一个事件javascript函数。

<script type="text/javascript">

    function CookiebotCallback_OnAccept() {
        window.location.reload(true);
        if (Cookiebot.consent.statistics)
        {

        }
    }
</script>

此脚本会导致无限刷新,因为每次加载页面时都会运行该函数。我该怎么做才能使这个功能只在被调用时运行而不是每次加载都会自动运行?

2 个答案:

答案 0 :(得分:1)

我的解决方案是在localStoragesessionStorage中创建一个标志变量,然后检查是否已有变量,跳过调用重新加载。

<script type="text/javascript">   
    function CookiebotCallback_OnAccept() {
      if(!sessionStorage.getItem('isReloaded')) {
        sessionStorage.setItem('isReloaded', true);

        window.location.reload(true);

        if (Cookiebot.consent.statistics)
        {

        }
      }
    }
</script>
// you can also clear the variable to trigger the reload again.
// By: sessionStorage.removeItem('isReloaded');
// Note: the sessionStorage will be cleared each time you close the browser, 
// while localStorage is only by uninstalled the browser or manually.

答案 1 :(得分:1)

无需处理操纵cookie或任何其他hacky解决方案。 JavaScript提供了一些本机事件侦听器,用于验证文档是否已成功加载。基本上你的三个选择是:

Inline HTML example
1. <body onload='fooBar()'>

Native DOM events that can be invoked within an HTML snippet,
or more preferably, within there own parent function to offer
more fine grained control over invocation.
2. document.onload = ()=>
3. window.onload = ()=> 
    i.e:
        const foo = () => document.onload
        const bar = () => window.onload

     Invoking them anywhere within you code base as necesary without 
     rigidly coupling your JavaScript code within your HTML

首选方法是window.onload,因为document对于何时加载并不完全诚实。

遵循上面使用内联方法的逻辑,这是一个可行的替代方案:

// Add the following HTML immediately after your opening `body` tag.
// This ensures no competing JS scripts can run before the one we have 
// here.
<script type="text/javascript">

    (() => {
      const runMeAfterPageLoad = () => 
        Cookiebot.consent.statistics ? // If true logic here : null

        if (window.addEventListener) {
          window.addEventListener('load', runMeAfterPageLoad, false)
        }
        else if (window.attachEvent) {
         window.attachEvent('onload', runMeAfterPageLoad)
        }
        else window.onload = runMeAfterPageLoad
    })()

</script>