Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 702
user3446254 Avatar asked Mar 21 '14 11:03

user3446254


People also ask

How do you add script tags to react JS?

Installation: Open a terminal inside your ReactJS project folder and write the following code to install react-script-tag Package. Import 'ScriptTag' component: Import the built-in 'ScriptTag' component from the react-script-tag library at the top of the file where we want to add the script tag.

Can we use script tag in js file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.


1 Answers

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.

like image 130
Michael Pratt Avatar answered Oct 11 '22 06:10

Michael Pratt