Next.js Discord

Discord Forum

Next/Script: add event listener before loading/executing script

Unanswered
Singapura posted this in #help-forum
Open in Discord
SingapuraOP
I load a third party script from the local filesystem and need to set up an event listener that will detect when a certain event is dispatched by the script (the script is self-executing). The script needs to be loaded on every page, so we were using next/script inside _document.js to load the script and registering an event listener in _app.js. However, it seems that the event listener may not be registered by the time the event is dispatched.

I looked through the documentation to see if any of the Script callbacks (onLoad, onReady) would work but it appears that they don't work when using Script inside _document. Should I move this script to _app.js and add the event listener inside useEffect instead?

1 Reply

SingapuraOP
A further oddity: it seems like when using next/script, this script will only execute if I use the beforeInteractive strategy, which means I have to place it inside _document.js according the docs. If I just use a normal script tag inside _app.js it executes the script as expected.