Next.js Discord

Discord Forum

Script tag doesn't load the script until the page is reloaded

Answered
Say's Phoebe posted this in #help-forum
Open in Discord
Say's PhoebeOP
The video best describes the issue
This is the source code for the script tag:
https://github.com/RohanVashisht1234/litexlthemes/blob/main/src/app/themes/%5Bslug%5D/page.tsx#L198
Answered by Toyger
your script loads fine, problem that your logic inside script wrong
you have something like
document.getElementById('my_toast')

but at the moment when script loads on another page this element not exist,
and when you go to new page script already executed.
so you need to move your event listeners to document something like this
function handleEvent(event) {
    if (event.target.classList.contains('your-class-name')) {
        console.log('Event handled for elements with the class name');
    }
}
document.addEventListener('click', handleEvent);


or maybe using MutationObserver

or better use something like that https://www.npmjs.com/package/react-copy-to-clipboard directly in nextjs
View full answer

3 Replies

Say's PhoebeOP
the page needs to be reloaded for the script tag to work
Toyger
your script loads fine, problem that your logic inside script wrong
you have something like
document.getElementById('my_toast')

but at the moment when script loads on another page this element not exist,
and when you go to new page script already executed.
so you need to move your event listeners to document something like this
function handleEvent(event) {
    if (event.target.classList.contains('your-class-name')) {
        console.log('Event handled for elements with the class name');
    }
}
document.addEventListener('click', handleEvent);


or maybe using MutationObserver

or better use something like that https://www.npmjs.com/package/react-copy-to-clipboard directly in nextjs
Answer