React: how to load javascript file from cdn server in a component?

Created on 20 Aug 2015  Â·  4Comments  Â·  Source: facebook/react

I want to load a javascript file form cdn server, but don't want to put it in tag, so I wrote it in a component like this:

var Component = React.createClass({
  render: function () {
    return (
      <div>
        ...
        <script src='//cdn-file-link' />
      </div>
    )
  }
})

but it didn't worked, what should i do?

Most helpful comment

@zpao How to import 'https://unpkg.com/react@15/dist/react.min.js' cdn in my ReactJS file? not in HTML file by using script tag.

All 4 comments

Questions like this are best addressed on stack overflow. Since this is not a github issue, I'm going to close it out.

Rendering a script tag is probably not what you want to be doing. The biggest question is, why are you trying to render a script tag inside a div? If you're trying to render an outside module, you should probably be invoking that module via javascript in your componentDIdMount function. It's hard to tell exactly, since you didn't provide much background about what you were trying to accomplish. I'd recommend posting a more detailed statement of your goal on stackoverflow and see what people there think.

The problem is that <script> elements created with innerHTML don't execute, which also means they don't fetch the external resource. This is an issue with React, but it is longstanding and there are workarounds. There is also the issue that if we ever use createElement, those scripts will suddenly start executing.

@Jensyn - Since there's no way for us to do this reliably right now, what you might want to do is do the element creation manually after mounting, or maybe pull out that functionality so that you can create script elements in a shared way. Eg…

var _loaded = {};
function addScript(url) {
  if (!loaded[url]) {
    var s = document.createElement('script');
    s.src = url;
    document.head.appendChild(s);
    _loaded[url] = true;
  }
}

Thank you so much for your help! And it was just what I wanted. @zpao @jimfb . Perhaps I should do a more detailed description on stack overflow, thank you! @jimfb

@zpao How to import 'https://unpkg.com/react@15/dist/react.min.js' cdn in my ReactJS file? not in HTML file by using script tag.

Was this page helpful?
0 / 5 - 0 ratings