Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nextjs script doesn't work after router has changed

My external scripts stop to work after the router changes (**When the user click on any link**)

inside _app.js

  import Script from "next/script";

        <Script
          async
          type="text/javascript"
          src="//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js"
        />
  

What it look like on first render
enter image description here

What it look like after router changes

2

What i tried so far

Put it inside the Head tag - this makes it not work at all.

Put the scripts inside _document, this makes the same error.

like image 467
Charlie Østergaard Avatar asked Oct 28 '25 04:10

Charlie Østergaard


1 Answers

Add the bellow script on your main layout.

Import useEffect and useRouter

import { useEffect } from "react";
import { useRouter } from "next/router";

Assign file path to scripts object.

let scriptRefArr = []

  const { route } = useRouter()

  useEffect(() => {
    if (route) {
      const scripts = ['/assets/libs/tiny-slider/min/tiny-slider.js', '/assets/libs/tobii/js/tobii.min.js', '/assets/libs/feather-icons/feather.min.js', '/assets/js/plugins.init.js', '/assets/js/app.js'];

      for (let item of scripts) {
        loadScript(item);
      }
    }

    return () => {
      if (scriptRefArr.length > 0) {
        removeScript()
      }

    }

  }, [route]);

  const loadScript = (src) => {
    const script = document.createElement('script');
    script.src = src;
    script.async = true;
    if (!scriptRefArr.find(item => item.url === src)) {
      document.body.appendChild(script);
      scriptRefArr.push({ url: src, script })
    }
  }

  const removeScript = () => {
    scriptRefArr.forEach(item => {
      if (document.body.contains(item.script)) {
        document.body.removeChild(item.script);
      }
    })

  }
like image 182
Fardin Ahsan Avatar answered Oct 30 '25 12:10

Fardin Ahsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!