JavaScript事件功能运行一个页面加载



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

<script type="text/javascript">
    function CookiebotCallback_OnAccept() {
        window.location.reload(true);
        if (Cookiebot.consent.statistics)
        {
        }
    }
</script>

此脚本会导致无限刷新,因为每次加载页面时该功能运行。我该怎么做才能使此功能仅在调用时运行并且不是自动的每个页面加载?

无需处理操纵cookie或任何其他黑客解决方案。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>

我的解决方案是在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.

最新更新