在hugo模板上使用giscus的页面加载性能问题

问题描述 投票:0回答:1

我正在开发一个 Hugo 网站并集成 Giscus 以征求意见。我想在页面上发生鼠标移动或滚动事件后动态加载 Giscus 脚本。

我想修改这个脚本,以便当用户移动鼠标或滚动页面时加载 Giscus 脚本。我尝试为鼠标移动和滚动添加事件侦听器,但没有得到所需的结果。

这是我的尝试:

<!-- Modified Giscus Script with Event Listeners -->
  <script type="text/javascript">
    (function() {
      const themeToggle = document.querySelector('.darkmode-toggle input');
      const light = 'light';
      const dark = 'dark';
      let isDark = localStorage.theme === dark || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches);
      let theme = isDark ? dark : light;
  
      const s = document.createElement('script');
      s.type = 'text/javascript';
      const dataset = {
          repo: '{{ .repo }}',
          repoId: '{{ .repoId }}',
          category: '{{ .category }}',
          categoryId: '{{ .categoryId }}',
          mapping: '{{ .mapping }}',
          reactionsEnabled: '{{ .reactionsEnabled }}',
          emitMetadata: '{{ .emitMetadata }}',
          theme: theme,
          lang: '{{ .lang }}',
      };
      s.src = 'https://giscus.app/client.js';
      s.crossorigin = 'anonymous';
      s.async = true;
      Object.entries(dataset).forEach(function(a) {
          return s.dataset[a[0]] = a[1];
      });
  
      const curScriptElement = document.currentScript;
      curScriptElement.parentNode.insertBefore(s, curScriptElement);
  
      function sendMessage(message) {
        const iframe = document.querySelector('iframe.giscus-frame');
        // console.log(iframe);
        if (!iframe) return;
        iframe.contentWindow.postMessage({ giscus: message }, 'https://giscus.app');
      }
  
      function loadGiscusScript() {
        if (!s.parentElement) {
          curScriptElement.parentNode.insertBefore(s, curScriptElement);
        }
      }
  
      document.addEventListener('mouse-move', loadGiscusScript);
      window.addEventListener('scroll-window', loadGiscusScript);
  
      themeToggle.addEventListener('change', function () {
        if (this.checked) {
          theme = dark;
        } else {
          theme = light;
        }
        sendMessage({
          setConfig: {
            theme: theme,
          }
        });
      });
    })();
  </script>

然而,这似乎并没有达到预期的效果。鼠标移动或滚动后,Giscus 脚本不会加载。

有人可以帮我理解我可能做错了什么,并建议一个在鼠标移动或滚动事件后动态加载 Giscus 脚本的解决方案吗?

任何见解或替代方法将不胜感激!预先感谢您。

hugo hugo-theme
1个回答
0
投票

您有一个拼写错误,没有您所演示的此类事件。相反,事件是

mousemove
scroll

但是,这不是一个理想的方法。按照编码,您将不断触发事件侦听器。您可以通过添加

once
选项来完成此操作,如下所示:
listener.addEventListener(eventName, handler, { once: true })

但是您应该查看的是Intersection Observer,当元素处于视图中时会触发

© www.soinside.com 2019 - 2024. All rights reserved.