Is there a way to unload a script from memory in NextJS?

30 Views Asked by At

I am building a website with 4 pages.

The homepage has 4 scripts injected, 3 of which are a one-time code execution, but the last one is a looping event of a 1.5 seconds interval.

When the route changes to another page, the looping script stays in memory and keeps executing, printing in the console that it can't find a specific element, as expected.

I have tried to force a redirect where the entire page is requested.

Although I don't have a problem with 1 page doing this, and adding a small delay, I believe there has to be a better way to do this.

I am using NextJS/Scripts component to load the scripts. When changing pages, the scripts remain in the html body. Even if unmounting them from the document, they remain running in memory

<Script src="scripts/script1.js" strategy="lazyOnload" />
<Script src="scripts/script2.js" strategy="afterInteractive" />
0

There are 0 best solutions below