【问题标题】:Gatsby-js client side javascript inline in blog post博客文章中的 Gatsby-js 客户端 javascript 内联
【发布时间】:2018-05-16 09:50:54
【问题描述】:

我正在尝试使用 Gatsby-JS 设置博客。我在 Markdown 中有一些包含内联 javascript 的帖子。

举个例子:

<script>window.alert("hello");</script>

我使用命令“Gatsby serve”测试网站

当我通过博客的索引浏览到我的帖子时。该脚本未执行。在 Web 控制台中没有错误。

在帖子页面本身上时。如果我按 F5 或 ctrl-f5 则会显示“hello”警报。

将站点上传到 github 页面后,此行为会发生变化。我无法通过 F5 或通过索引导航来执行脚本。只有当我按下 ctrl+F5 时才会执行脚本。

可以在此处找到实时测试博客(它显示多个警报并尝试按情节加载)。 https://dwjbosman.github.io/lstm-neural-network-for-sequence-learning/

【问题讨论】:

    标签: javascript webpack gatsby


    【解决方案1】:

    查看这个问题React: Script tag not working when inserted using dangerouslySetInnerHTML

    由 React 的 dangerouslySetInnerHTML 插入的 HTML 脚本不会被执行。链接的问题有一个解决方法,也许您可​​以使用。

    【讨论】:

      【解决方案2】:

      上一个答案为我指明了正确的方向。

      我给所有的内联脚本一个属性 data-my-script。接下来,我将以下内容添加到 layouts/index.jsx(不是 html.jsx,因为它仅在服务器端呈现)。

      componentDidMount() {
          let scripts = window.jQuery.find('[data-my-script]')
          console.log(scripts);
              scripts.forEach(function forEachScript(element) {
                  const script = window.jQuery(element).text();
                  window.eval(script);
              });
      
        }
      
        render() {
          const { children } = this.props;
          return (
            <Navigation config={config} LocalTitle={this.getLocalTitle()}>
              <div ref={contentElement => (this.contentElement = contentElement)}>
                <Helmet>
                  <meta name="description" content={config.siteDescription} />
                  // for plotly inside notebooks
                  //  <script src="https://cdn.plot.ly/plotly-latest.min.js" />
                  <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"/>
                  <script src="https://code.jquery.com/jquery-3.2.1.min.js"/>
                </Helmet>
                {children()}
              </div>
            </Navigation>
          );
        }
      }
      

      【讨论】:

        【解决方案3】:

        Dinne 的解决方案对我有用。好东西! :)

        我确实需要避免使用 JQuery,所以我在这里发布了一个不依赖它的版本:

        componentDidMount() {
        
          // Allow in-line JS scripts to be run
          let scripts = document.querySelectorAll('[data-inline-script="data-inline-script"]');
          scripts.forEach(function forEachScript(element) {
            const script = element.innerHTML;
            window.eval(script);
        });
        

        这将适用于以下 HTML:

        <script data-inline-script="data-inline-script">
            console.log("this works");
        </script>
        

        我在一个非常基本的静态网站上使用它。老实说,我不确定我有多喜欢使用 eval(),但它应该不会对我的用例造成伤害。

        更新 虽然上面的方法确实有效,但我还需要包含使用

        【讨论】:

          猜你喜欢
          • 2021-01-04
          • 2021-04-17
          • 1970-01-01
          • 2021-07-11
          • 1970-01-01
          • 2019-01-13
          • 2020-10-13
          • 2020-06-06
          • 1970-01-01
          相关资源
          最近更新 更多