简体   繁体   English

使用 NextJS 将计时器设置为 append 将脚本添加到 TypeScript 中的主体标记

[英]Setting a Timer to append a Script to Body Tag in TypeScript using NextJS

I have very little experience with Typescript, I'm more of a Vanilla JavaScript person that works with react.我对 Typescript 的经验很少,我更像是一个与 React 一起工作的 Vanilla JavaScript 人。

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:我的想法是创建脚本的 JSX 元素,并使用计时器将其发送到 document.body append,但我遇到了 typescript 的问题。我的代码如下,后面是错误:

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.我想我正在尝试弄清楚如何将参数类型从 Element 更改为 String 或 Node。

I have tried using the 'defer' attribute and also have tried using Next Js's tag with it's strategy, lazyOnload.我尝试过使用“延迟”属性,也尝试过使用 Next Js 的标签及其策略 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.如果有人确实使用 Podium Chat 小部件并且知道一个属性来分配脚本以便稍后加载,那也会非常有帮助,但我认为没有。

Thank you to anyone that reads this.感谢任何阅读本文的人。

You shouldn't mix JSX with traditional DOM manipulation methods.您不应该将 JSX 与传统的 DOM 操作方法混合使用。 As the error suggests, the thing you are appending is not actually an HTML element.正如错误所暗示的那样,您要附加的内容实际上并不是 HTML 元素。 It's a JSX expression (which has type JSX.Element) and can't be used there.它是一个 JSX 表达式(具有 JSX.Element 类型)并且不能在那里使用。

Do it with traditional DOM methods instead:改为使用传统的 DOM 方法:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM