导航离开然后返回时在单页网站上加载 javascript 时出现问题

Issues loading in javascript on single page website when navigating away and then returning

这是我的网站:https://memsmosaics.com/

我正在努力使我的网站成为单页网站。当网站最初加载到 index.html 时,它会按预期运行。此时底部部分通过以下函数很好地从 gallery.html 加载:

<script>
  $(document).ready(function() {
    $('#js-content').load('/gallery.html');

    $('#js-navigation a').click(function(e) {
      e.preventDefault();
      $("#js-content").load(e.target.href);
    })
  });
</script>

当我导航到关于部分,然后通过单击左上角的 'memsmosaics' return 返回主页部分时,图库部分不再正常工作。看起来 javascript 不再适用于做它以前做的事情——比如对齐图像,以及按 'sold' 和 'for sale' 过滤。

我试过将相关脚本标签从index.html移动到gallery.html,但这并没有解决问题。我不确定还能尝试什么。

感谢您的帮助!

您可以在加载后监听 popstate 事件,如下所示:

const initGallery = () => {
    if(location.hash === '#new-section' || location.path === '/') {
       $('#js-content').load('/gallery.html');

       $('#js-navigation a').click(function(e) {
         e.preventDefault();
         $("#js-content").load(e.target.href);
       })
    }
}

window.addEventListener('popstate', initGallery)

$(document).ready(initGallery);

导航时触发。这是一篇提供更多见解的文章:https://gomakethings.com/how-to-detect-when-the-browser-url-changes-with-vanilla-js/

编辑说明: 您 运行 遇到的问题是您的处理程序 在加载时被添加,因此当画廊被删除时,您已经分离了 DOM 节点,而且它们永远不会重新附加,因为加载事件仅在初始页面加载时触发。这会造成内存泄漏。

您可以在此处了解有关分离的 DOM 节点的更多信息:https://www.tutorialspoint.com/how-can-detached-dom-elements-cause-memory-leak-in-javascript

您可以更新上面的代码以删除点击监听器。我不太熟悉 jQuery,但文档演示了一个 off 方法,因此您的更新代码也可以如下所示:

const initGallery = () => {
    const onClick = (e) => {
         e.preventDefault();
         $("#js-content").load(e.target.href);
    }
    
    const btn = $('js-navigation a')

    if(location.hash === '#new-section' || location.path === '/') {
       $('#js-content').load('/gallery.html');
       
       btn.click(onClick)
       return
    }
    if(btn) {
        btn.off('click', onClick)
    }
}

根据 popstate 的定义,这应该有效:

When the transition occurs, either due to the user triggering the browser's "Back" button or otherwise, the popstate event is near the end of the process to transition to the new location.