Creating new instances of external script in React - javascript

I've been stuck with integrating external script in my React application.
The idea is to use external html/js widget that will suggest addresses based on the data in the input field.
The widget requires two things:
<script type="text/javascript" src="https://some.address.com/widget.min.js"></script> - must be inside the html head tag.
<script> var widget = new jsWidget ({"detail1":"foo","detail2":"bar","lang":"en"});</script> - must be inside the html body tag.
My question is - how can I create new instance of an external script if the given item is not imported as a module? I know that the first part can be resolved with useEffect hook. However, if I try to make new instance of jsWidget, the code editor throws an error saying that jsWidget is not defined.
The given widget works fine in pure html. For example:
<html>
<head>
<script1></script1>
</head>
<body>
<script2></script2>
</body>
</html>
I've been stuck with this for a long time now and I can't figure out a way how to fix this. I would be really thankful if someone could give some advice.

maybe not the best method. i think it'll works
var script1 = document.createElement("script");
script1.type = "text/javascript";
script1.src = "https://some.address.com/widget.min.js";
var script2 = document.createElement("script");
script2.innerHTML = 'new jsWidget ({"detail1":"foo","detail2":"bar","lang":"en"});';
document.head.appendChild(script1);
script1.onload = function () {
document.body.appendChild(script2);
};

Related

How to display external <script> using div in Reactjs?

I am trying to learn how to display small widgets (for example plane tickets brower) onto my website built in Reactjs. The code that's supposed to work instantly according to the provider is as below ("just copy and paste into website"):
<div id="widget" data-widget="search" data-affiliate="873" data-campaign="873-"></div>
<script src="https://widget.wakacje.pl/v2/public/js/widgets/search-widget.js?c=widget" async></script>
I tried to Google for answers and my idea atm looks like this:
function OfferBrowser() {
const script = document.createElement("script");
script.src = "https://widget.wakacje.pl/v2/public/js/widgets/search-widget.js?c=widget";
script.async = true;
return(
<div id="widget" data-widget="search" data-affiliate="873" data-campaign="873-"></div>
)
}
The other this I tried was also to put {script} into the tag like this, but it doesn't work as well.
<div id="widget" data-widget="search" data-affiliate="873" data-campaign="873-">{script}</div>
How should I approach this?
While I don't know React, I believe I have found the problem with the second chunk of code. You have created a script element, but have not added it to the DOM, and therefore it's not loading the script.
After looking around for a bot, I believe I've found a fix.
const script = document.createElement("script");
script.src = "https://widget.wakacje.pl/v2/public/js/widgets/search-widget.js?c=widget";
script.async = true;
// append the script tag to the body
document.body.appendChild(script);
I think this needs to run after the component is mounted, so that the div is in the DOM.

Changing the script reference in HTML file when a button is pressed

I am trying to change the entire layout of my site when the submit button is pressed. So I find it easier to switch between two JS scripts rather than trying to cram everything into one, but the page isn't responding to change in script, even though the console shows the change in the script reference. I have added the relevant snapshots below. Thank you for reading my problem...
<script src="prac.js"></script>
button.addEventListener('click', function(e){
document.getElementsByTagName('script')[0].src = 'main.js';
console.log(document.getElementsByTagName('script')[0]);
});
EDIT : I am new to this forum so I did not know about the code insertion. I'm sorry about that. Also the console message essentially showed an expexted change in script reference but the website layout did not change.
EDIT 2 : The suggested deletion and appending of new script does indeed work, but can someone explain why altering the current script tag ends in failure?
Remove the script element from DOM and add another script like this:
<html>
<head>
<script src="demo1.js"></script>
</head>
<script>
window.onload = function(){
var firstScript = document.getElementsByTagName('script')[0]; //get first script
document.getElementsByTagName('head')[0].removeChild(firstScript); //removing it from DOM <head> tag
var secondScript = document.createElement('script'); //creating another script
secondScript.src = "demo2.js"; //adding source to it
document.getElementsByTagName('head')[0].appendChild(secondScript); //adding script to DOM
};
</script>
</html>

Loading javascript import into React application

Edit
I decided to try adding the script tags to the index.html file and conditionally rendering them.
<script type="text/javascript">
var $show_stuff = 'no';
var $add_stuff = 'yes';
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.example.com/includes.php?stuff=true';
document.getElementById('feed').appendChild(script);
</script>
Then in the component I want the feed to show up I did this,
<div id="credit-feed" />
I also tried conditionally rendering the script tag in the index.html file like this,
if(window.location.href === "localhost:3000/my/path" ) { script tag... }
These both do not work as well. The script tag does not show up in the div in the first example and the second does show the script tag but it does not render.
But, when I add the script tag like normal to the head of the HTML file, the feed renders as I would expect.
Background
We do business with a company that provides us a Javascript script tag which appends the data from it's response into the body of our web page. We have had a PHP site for the past 8 years without problems but now that we are switching to React, we can not figure out the correct way to use this tag in the component it will live.
Problem
When we add the script tag to the React component, it does not append the correct data to the page. In fact it does not append any data to the page.
Example
I have tried to load the script tag like normal,
<script type="text/javascript">
var $somevar = "false";
var $addjquery = "yes";
</script>
<script
type="text/javascript" src="https://www.example.com/do/deef.php?feedtype=all ">
</script>
Another way I have tried in the React component,
componentWillMount() {
const script = document.createElement('script');
const $somevar = 'false';
const $addjquery = 'yes';
script.src = 'https://www.example.com/get/feed.php?&data=all';
script.async = true;
document.body.appendChild(script);
}
Question
What is the correct way to load the script tag so it will append the data to my application?
Usually with a React app, you will have an index.html file that contains the React component. You should put the <script> reference inside the html file. So I would definitely use the first approach you mention. If it's not loading, can you check the browser inspector and find out what kind of error you are getting? For one thing, you should remove the empty white space from the URL. That could be the issue.

Trouble loading js

I'm sorry in advance if this is simple or if it just can't be done. Basically, I am trying to load an age verification js on my site, but I am trying to chose between different pages depending on the legal drinking age in different countries.
If I load the script simply, it works fine:
<script type="text/javascript" src="https://av.ageverify.co/jsfr/singlemalt.18.js"></script>
However, if I trying to do any sort of modification to this script, it won't load at all. For example, if I try to set the src to a variable (that I would call in a different script, it fails to load).
<script>
url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
</script>
<script type="text/javascript" src=url></script>
Any ideas would be greatly appreciated!
EDITED:
Additional info:
I tried to use getScript as people have suggested but also had issues with it:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$.getScript("https://av.ageverify.co/jsfr/singlemalt.18.js");
</script>
or this method:
function loadJs() {
var url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
}
This last one seems to work with other simple scripts, but maybe this particular script is looking for some sort of browser condition? Any suggestions on how to figure that out or what to look for? There should be an age verification page that pops up, asking your age.
HTML tags do not understand variables. You need to use a URL for the src attribute. HTML has no idea what your JavaScript variables are.
If you want to load the .js file this way, you need to use JavaScript. What you can do is create a new <script> tag then append it to the page.
var url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
If you are using jQuery, this is basically what $.getScript does.
var url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
$.getScript(url);

Looking for an elegant way to load JS and execute it

I'm new into JavaScript and I really like jQuery and hate when it comes to writing some cumbersome code to get simple things done.
I'm currently trying to load an external JS dynamically and execute it (to communicate with Google Translate API).
The sample code creates a script tag, sets its src and appends it to document's head to execute it:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;
// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
I wonder if there's any one-liner in jQuery for this.
$.getScript('https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + $('#sourceText').html());
Try this:
http://api.jquery.com/jQuery.getScript/
HeadJS is made for such use, this is easy and optimized way to include scripts This will helps you sure.
basic Method: ( took 800ms)
<script src="https://github.com/DmitryBaranovskiy/raphael/raw/master/raphael.js"></script>
<script src="https://github.com/jquery/jquery-ui/raw/master/jquery-1.4.4.js"></script>
<script src="https://github.com/smith/scripty2/raw/master/lib/prototype.js"></script>
<script src="https://github.com/headjs/www/raw/master/content/test/jquery-ui.js"></script>
<script src="https://github.com/kosmas58/compass-jquery-plugin/raw/master/lib/jslint.js"></script>
using head.js (took 700 ms)
<script src="../media/js/head.min.js"></script>
<script>
head.js("https://github.com/DmitryBaranovskiy/raphael/raw/master/raphael.js")
.js("https://github.com/jquery/jquery-ui/raw/master/jquery-1.4.4.js")
.js("https://github.com/smith/scripty2/raw/master/lib/prototype.js")
.js("https://github.com/headjs/www/raw/master/content/test/jquery-ui.js")
.js("https://github.com/kosmas58/compass-jquery-plugin/raw/master/lib/jslint.js");
</script>
see the testcase

Categories

Resources