Gatsby-js client side javascript inline in blog post

南楼画角 提交于 2019-12-06 12:39:40

The previous answer pointed me in the right direction.

I gave all the inline scripts an attribute data-my-script. Next I added the following to layouts/index.jsx (not html.jsx as this is rendered only server side).

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

Dinne's solution worked for me. Nice one! :)

I did need to avoid the use of JQuery though so I have posted here a version that doesn't rely on it:

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

This will work with the following HTML:

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

I am using this on a very basic static site. I'm not sure how much I like using eval() to be honest but it should cause no harm in my use-case.

Update Although the above does work, I also need to include scripts using <script src="..."> which doesn't work :( This feels quite hacky too.

Checkout this question React: Script tag not working when inserted using dangerouslySetInnerHTML

Script in HTML that is inserted by React's dangerouslySetInnerHTML won't get executed. The linked question has a work around that perhaps you can use.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!