【问题标题】:Using an external script in React / Meteor在 React / Meteor 中使用外部脚本
【发布时间】:2016-10-14 06:21:03
【问题描述】:

我正在尝试在 Meteor 的反应组件中包含一个外部脚本。 我尝试像这样将脚本标签放在我的组件中:

TheLounge = React.createClass({
  render() {
    return (
      <div>
        <div className="main">
          {/* Uberflip Embedded Hub (Use this to generate the frame below) */}
          <script>var ufh_top_offset = 0, ufh_bottom_offset = 0;</script>
          <script type="text/javascript" src="https://thelounge.tullyluxurytravel.com/hubsFront/embed_iframe?u=https%3A%2F%2Fthelounge.tullyluxurytravel.com%2Fh%2F%3Fembedded%3D1%26offsetTop%3D0%26offsetBottom%3D0%26hideHeader%3D1%26hideBanner%3D0%26hideFooter%3D1%26hidePriNav%3D0%26hideSecNav%3D0%26linkBreakOut%3D0"></script>
          {/* /End Uberflip Embedded Hub */}

        </div>
        <Footer />
      </div>
    );
  },
});

这使得页面第一次加载(通过另一个页面或刷新)时可以正常工作。但是,当导航到另一个页面并返回时,脚本不会再次加载。

到目前为止,我尝试了以下方法:

  • 在 componentDidMount 和 componentDidUpdate 中注入脚本,如下所示:

在componentDidMount和componentDidUpdate中:

var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
// Tested the line below with body, head, and a div with specific id.
document.getElementsByTagName("body")[0].appendChild(script);

我也尝试过使用这些包:

但是,使用上述所有四种方法时,我都会遇到错误:

Error: Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

我意识到这是因为我尝试加载的脚本使用 document.write();

我要尝试的东西已经不多了,我很欣赏有关如何将此脚本包含到 React 组件中的新想法。

【问题讨论】:

    标签: javascript jquery meteor reactjs


    【解决方案1】:

    正文或模板中的标签不是由 Meteor 执行的,它们被解析然后由 Meteor 的模板系统处理。试试 jQuery getScript 函数:

    componentWillMount() {
      $.getScript('https://thelounge.tullyluxurytravel.com/hubsFront/embed_iframe?u=https%3A%2F%2Fthelounge.tullyluxurytravel.com%2Fh%2F%3Fembedded%3D1%26offsetTop%3D0%26offsetBottom%3D0%26hideHeader%3D1%26hideBanner%3D0%26hideFooter%3D1%26hidePriNav%3D0%26hideSecNav%3D0%26linkBreakOut%3D0');
    }
    

    【讨论】:

    • 请注意,这永远不会缓存脚本
    【解决方案2】:

    我没有尝试过这个,但我读了这个是为了大火。或许能帮上忙

    https://maxlibin.com/meteor-include-external-javascript-files/

    【讨论】:

      猜你喜欢
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 2017-10-15
      相关资源
      最近更新 更多