简体   繁体   English

为什么在运行时添加<script>标记不会加载javascript文件? (with react.js)

[英]Why adding a <script> tag at runtime doesn't load the javascript file? (with react.js)

I have this react.js script that adds the following code into the html 我有这个react.js脚本,它将以下代码添加到html中

// returned by the render method
React.DOM.div({
    dangerouslySetInnerHTML:  {
        __html: '<script type="text/javascript" async="" src="//myapp.disqus.com/embed.js"></script>'
    }
})

Now my html looks like: 现在我的HTML看起来像:

<script type="text/javascript" async="" src="//myapp.disqus.com/embed.js"></script>

Which seems perfect but the problem is that it doesn't load the script. 这似乎很完美,但问题是它不加载脚本。 The script tag is inserted into the middle of the body, nested within some other div tags. 脚本标记插入到正文的中间,嵌套在其他一些div标记中。

What might be the problem? 可能是什么问题? Thanks 谢谢

Rendering the script tag to the page with react isn't the right solution - I coudln't get it to work with JSX, I assume the same applies here. 将脚本标记渲染到带有react的页面是不正确的解决方案 - 我不能让它与JSX一起工作,我认为这同样适用于此。 Not sure why, but just add it the plain old javascript way: 不知道为什么,但只需添加简单的旧JavaScript方式:

    var script = document.createElement("script");

    script.src = "//myapp.disqus.com/embed.js";
    script.async = true;

    document.body.appendChild(script);

Put that in the componentWillMount of your root component. 将它放在根组件的componentWillMount中。

I just added Disqus to my React app yesterday. 我刚刚在我的React应用程序中添加了Disqus。 I used the 'react-disqus-thread' module and had it up and running in no time. 我使用了'react-disqus-thread'模块,并立即启动并运行。

Here it is on github: https://github.com/mzabriskie/react-disqus-thread 这是在github上: https//github.com/mzabriskie/react-disqus-thread

And npm: https://www.npmjs.com/package/react-disqus-thread 和npm: https ://www.npmjs.com/package/react-disqus-thread

The component takes the following props: 该组件采用以下道具:

  • shortname - This is 'myapp' in //myapp.disqus.com/embed.js shortname - 这是//myapp.disqus.com/embed.js中的'myapp'
  • identifier - a unique blogId that can identify your blog post if the url changes 标识符 - 一个唯一的blogId,可以在网址更改时识别您的博客帖子
  • title 标题
  • url - if you do not provide this, the module will detect the url and provide it. url - 如果你不提供这个,模块将检测网址并提供它。

Which browser you tested ? 您测试了哪种浏览器? If you use async="true" in your script tag, it won't block. 如果在脚本标记中使用async =“true”,则不会阻止。 But that's only supported by a couple of browsers yet . 但这只是由几个浏览器支持。

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

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