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

user3446254 picture user3446254 · Mar 21, 2014 · Viewed 10.7k times · Source

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

Answer

Michael Pratt picture Michael Pratt · Jun 28, 2016

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.