简体   繁体   English

页面更改时未加载外部脚本

[英]External script not loading on page change

I am trying to add a Trustpilot widget to my Gatsby.js website.我正在尝试将 Trustpilot 小部件添加到我的 Gatsby.js 网站。 It is required to load an external script from Trustpilot CDN.需要从 Trustpilot CDN 加载外部脚本。

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

I have tried multiple ways to add this script to my component.我尝试了多种方法将此脚本添加到我的组件中。 The first thing I tried was React Helmet.我尝试的第一件事是 React Helmet。 I added using the following code:我使用以下代码添加:

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

The script seems to load when I initially load a page.当我最初加载页面时,该脚本似乎已加载。 Once I navigate to a different page, the styling goes away.一旦我导航到不同的页面,样式就会消失。 As I reload, it comes back.当我重新加载时,它又回来了。

I tried adding the script inside componentDidMount()我尝试在 componentDidMount() 中添加脚本

componentDidMount() {
    var addScript = document.createElement('script');
    addScript.setAttribute('src', '//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js');
    document.body.appendChild(addScript);
}

If you want your script (or any other component) to be persistent through your site, you need to use wrapPageElement or wrapRootElement APIs.如果您希望您的脚本(或任何其他组件)在您的站点中持久存在,您需要使用wrapPageElementwrapRootElement API。 Both APIs are suggested to be placed in gatsby-browser.js as well as in gatsby-ssr.js建议将这两个 API 放在gatsby-browser.jsgatsby-ssr.js

Disclaimer: componentDidMount() will be triggered every time the DOM tree is loaded, it won't work for your use-case.免责声明:每次加载 DOM 树时都会触发componentDidMount() ,它不适用于您的用例。

The issue here is that you are adding a non-React asset, not a component.这里的问题是您添加的是非 React 资产,而不是组件。 You can try:你可以试试:

export const wrapPageElement = ({ element, props }) => {
  return <SomeWrapper {...props}>{element}</SomeWrapper>;
};

Then, create a component called SomeWrapper and place your <Helmet> :然后,创建一个名为SomeWrapper的组件并放置您的<Helmet>

const SomeWrapper = (props) =>{
 return <div>
           <Helmet>
             <script type="text/javascript" src="//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js" async /> 
          </Helmet>
          {props.children}
    </div>
}

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

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