Why adding a [removed] tag at runtime doesn't

2019-04-04 02:17发布

问题:

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 .