0

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:

  1. <script type="text/javascript" src="https://some.address.com/widget.min.js"></script> - must be inside the html head tag.
  2. <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.

1 Answer 1

0

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);
};
Sign up to request clarification or add additional context in comments.

1 Comment

instead of setTimeout use onload :) ` document.head.appendChild(script1); script1.onload = function () { document.body.appendChild(script2); };`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.