Skip to main content

Custom JavaScript

Since the Next.js router essentially operates like a single page application, it's important to make sure that your custom JavaScript is only loaded whenever the page renders. If you have JS that needs to be loaded on every page, you can wrap it in pageMount and pageUnmount events, depending on when you want it to run. For example:

<script>
// Runs every time a new page content is fully loaded in, after navigation
document.addEventListener('pageMount', function(){
// Your custom JS
console.log('New page has fully loaded in!')
})

// Runs right before page content is going to be destroyed, on navigation
document.addEventListener('pageUnmount', function(){
// Your custom JS
console.log('Old page is about to be removed...')
})
</script>