DEV Community

Cover image for Next.js Loads script tags but it doesn't execute them
Calvin Torra
Calvin Torra

Posted on • Originally published at calvintorra.com

2 2

Next.js Loads script tags but it doesn't execute them

Join The JS Fam Discord Here

A chill community where we pair-program, launch products and learn together

=====

Had another question on my website today about Next.js and custom scripts. This one bothered me a while ago too and I had a similar hack to the dev reaching out.

I had placed an "Immediately Invoked Function" inside a useEffect on my _app.js page.

Don't Do This

  useEffect(() => {
    var Tawk_API = Tawk_API || {},
      Tawk_LoadStart = new Date();
    (function () {
      var s1 = document.createElement("script"),
        s0 = document.getElementsByTagName("script")[0];
      s1.async = true;
      s1.src = "https://embed.tawk.to/60...";
      s1.charset = "UTF-8";
      s1.setAttribute("crossorigin", "*");
      s0.parentNode.insertBefore(s1, s0);
    })();
  }, []);
Enter fullscreen mode Exit fullscreen mode

This was to have a chatbox on my, on every page.

Placing the code inside the Head module that's built into Next now produces an error and provides a solution by using the Script module....which is also built-in.

This makes life a lot simpler. We can now create a separate file, paste our 3rd party script and link to it using the Script module.

Do This

pages/
public/
├─ chatbot/
│  ├─ script.js
Enter fullscreen mode Exit fullscreen mode

Then using this script across the entire app

import Script from "next/script";

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Script type="text/javascript" src="/chatbot/script.js" />
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay