Home > Enterprise >  Setting a Timer to append a Script to Body Tag in TypeScript using NextJS
Setting a Timer to append a Script to Body Tag in TypeScript using NextJS

Time:01-14

I have very little experience with Typescript, I'm more of a Vanilla JavaScript person that works with react.

What my client needs is to load a chat widget later after initial page load. My idea was to create a JSX element of the script and use a timer to append it to the document.body, but I'm running into issues with typescript. The code I have is below, followed by the error:

const podiumScript = (
    <script
      src="https://connect.podium.com/widget.js#API_TOKEN=5bd8dac4-3041-4f32-a378-e8cd53634bbb"
      id="podium-widget"
    ></script>
  );

  window.setTimeout(() => document.body.append(podiumScript), 5000);


const podiumScript: JSX.Element
Argument of type 'Element' is not assignable to parameter of type 'string | Node'.ts(2345)

I guess I'm trying to figure out how to change the argument type from Element to String or Node.

I have tried using the 'defer' attribute and also have tried using Next Js's tag with it's strategy, lazyOnload. However, the script needs delayed even more.

If anyone does use Podium Chat widget and knows of an attribute to assign the script to load later that would also be very helpful, but I don't think there is one.

Thank you to anyone that reads this.

CodePudding user response:

You shouldn't mix JSX with traditional DOM manipulation methods. As the error suggests, the thing you are appending is not actually an HTML element. It's a JSX expression (which has type JSX.Element) and can't be used there.

Do it with traditional DOM methods instead:

const podiumScript = document.createElement("script");

script.src = "https://connect.podium.com/widget.js#API_TOKEN=5bd8dac4-3041-4f32-a378-e8cd53634bbb";
script.id = "podium-widget";

// Should go in the head, too
window.setTimeout(() => document.head.append(podiumScript), 5000);
  • Related