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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22558004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:21:28  来源:igfitidea点击:

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

javascriptloadingreactjs

提问by user3446254

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.

这看起来很完美,但问题是它没有加载脚本。script 标签被插入到正文的中间,嵌套在其他一些 div 标签中。

What might be the problem?Thanks

可能是什么问题?谢谢

回答by Michael Pratt

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. Not sure why, but just add it the plain old javascript way:

使用 react 将脚本标签渲染到页面并不是正确的解决方案 - 我无法让它与 JSX 一起工作,我认为这同样适用于这里。不知道为什么,但只需以普通的旧 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 中。

回答by Matt Smith

I just added Disqus to my React app yesterday. I used the 'react-disqus-thread' module and had it up and running in no time.

我昨天刚刚将 Disqus 添加到我的 React 应用程序中。我使用了“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
  • identifier - a unique blogId that can identify your blog post if the url changes
  • title
  • url - if you do not provide this, the module will detect the url and provide it.
  • 短名称 - 这是 //myapp.disqus.com/embed.js 中的“myapp”
  • 标识符 - 一个唯一的 blogId,如果 url 发生变化,它可以识别您的博客文章
  • 标题
  • url - 如果你不提供这个,模块将检测到 url 并提供它。

回答by user3379655

Which browser you tested ? If you use async="true" in your script tag, it won't block. But that's only supported by a couple of browsers yet .

你测试的是哪个浏览器?如果您在脚本标签中使用 async="true",它不会阻塞。但这仅被几个浏览器支持。