简体   繁体   中英

Next.js Vanilla JS script won't run on deployment

I'm using Next.js to build a simple static site. The only vanilla JS script I have is for a mobile menu - to toggle it open and add a class to the body to prevent scrolling:

if (process.browser) {
  document.addEventListener('DOMContentLoaded', function() {

    let mainNav = document.querySelector('#menu')
    let navBarToggle = document.querySelector('#toggle')
    let noScroll = document.querySelector('body')

    navBarToggle.addEventListener('click', function () { 
      mainNav.classList.toggle('active')
      navBarToggle.classList.toggle('close')
      noScroll.classList.toggle('lock-scroll')
    })
  })
}

The if process.browser statement is something I had to add to get it to work on localhost, which works but only on the first load, eg when I first run next dev. After I navigate to another page it won't load, I guess because the page isn't being fully re-rendered, which the script needs or something?

Then when I deploy the site the toggle isn't working at all, even on first load.

Anyway, any help in getting this working would be much much appreciated!

process.browser has been deprecated, use type of window

if (typeof window !== "undefined") {
  document.addEventListener('DOMContentLoaded', function() {

    let mainNav = document.querySelector('#menu')
    let navBarToggle = document.querySelector('#toggle')
    let noScroll = document.querySelector('body')

    navBarToggle.addEventListener('click', function () { 
      mainNav.classList.toggle('active')
      navBarToggle.classList.toggle('close')
      noScroll.classList.toggle('lock-scroll')
    })
  })
}

if that solution doesn"t work, you can use dynamic import

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM