Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load external javascript through script tag

Tags:

reactjs

I am trying load a script dynamically using script tag. But I am not able to do it.

my render method is as below

render() {
<div> 
     <script type="text/javascript" language="javascript" src="//verify.authorize.net/anetseal/seal.js" ></script> 
     <a href="http://www.authorize.net/" id="AuthorizeNetText" target="_blank">Working. Yipee</a> 
</div>
}

I tried to use dangerouslySetInnerHtml but that is also not working.

I require this because, the script that is mentioned uses document.writeln. So I want it to display in this current div. I have no control over the script. It come from a third party.

like image 498
Abhijith Nagaraja Avatar asked Mar 07 '16 21:03

Abhijith Nagaraja


People also ask

How to add external JavaScript inside an HTML page?

The HTML <script> tag is used for declaring a script within your HTML document. Through this, you can define client-side JavaScript. But, what if you want to add external JavaScript inside an HTML Page? Well, you can easily do that too using the src attribute of the <script> tag. The following are the attributes of the <script> tag −

How to include external JavaScript files dynamically after the page has loaded?

script.innerHTML = 'alert ("Inline script loaded!")' As you can see, it’s easy to create and append new script elements, allowing us to include any number of external JavaScript files dynamically after a page has loaded. The real challenge isn’t loading the file – it’s knowing when the file has finished loading.

How to insert JavaScript in HTML with script tag?

There are two ways you can use the script tag to insert JavaScript in HTML. You can insert JavaScript directly into an HTML file. Here is an example of how you would do that using the script tag. I will go ahead and start with the script tag. Between the script tag, I will create a function that prints the text “Hello World” to the console.

How do I include external JavaScript files in an inline script?

Here’s an inline example: script.innerHTML = 'alert ("Inline script loaded!")' As you can see, it’s easy to create and append new script elements, allowing us to include any number of external JavaScript files dynamically after a page has loaded.


1 Answers

I believe you could be more specific on what should be done once the script has been loaded. Something like this should suit you well:

componentDidMount() {
    var aScript = document.createElement('script');
    aScript.type = 'text/javascript';
    aScript.src = " /*URL Goes Here*/ ";

    document.head.appendChild(aScript);
    aScript.onload = function() {
        document.getElementById(" /*DIV ID HERE*/ ").InnerHTML = /*YOUR CODE*/;
    };
}
like image 134
Carlos_E. Avatar answered Jan 03 '23 15:01

Carlos_E.