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

笑着哭i 提交于 2019-12-21 07:03:12

问题


I have this react.js script that adds the following code into the 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:

<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.

What might be the problem? Thanks


回答1:


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:

    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.




回答2:


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.

Here it is on github: https://github.com/mzabriskie/react-disqus-thread

And 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.



回答3:


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 .



来源:https://stackoverflow.com/questions/22558004/why-adding-a-script-tag-at-runtime-doesnt-load-the-javascript-file-with-rea

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