簡體   English   中英

導航離開然后返回時在單頁網站上加載 javascript 時出現問題

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

這是我的網站: https://memsmosaics.com/

我正在嘗試使我的網站成為單頁網站。 當網站最初在 index.html 加載時,它會按預期工作。 此時底部部分通過以下 function 從 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”返回主頁部分時,圖庫部分不再正常工作。 看起來 javascript 不再適用於做以前做的事情——比如對齊圖像,以及按“已售”和“待售”過濾。

我嘗試將相關腳本標簽從 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 節點,並且它們永遠不會重新連接,因為加載事件只會觸發在初始頁面加載時。 這會產生 memory 泄漏。

您可以在此處了解有關分離的 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的定義,這應該有效:

當轉換發生時,無論是由於用戶觸發瀏覽器的“后退”按鈕還是其他原因, popstate 事件都接近轉換到新位置的過程結束

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM