-2

I want external js file to insert scripts into html.

This is my wrong code:

var logScript = `<script>console.log('ok')</script>`;
document.body.appendChild(logScript);
6
  • Why do you want to do this? Some context will most likely mean we can give you a much better solution. Commented Dec 20, 2018 at 17:45
  • stackoverflow.com/questions/8085111/… Commented Dec 20, 2018 at 17:53
  • I have advertisement codes provided by ad networks. I need external js file to insert those codes into html in some scenarios Commented Dec 20, 2018 at 17:53
  • Why do you not just include the JS file in the page with script tags? Commented Dec 20, 2018 at 17:59
  • because exernal js decides if we need to use it. Commented Dec 20, 2018 at 18:03

2 Answers 2

0

This is the best way that I know of.

var logScript = document.createElement("script");
logScript.type = "text/javascript";
logScript.innerHTML = "console.log('test')";
document.body.appendChild(logScript);

The reason you have to do it this way, as far as I know, is because the browser thinks you are adding HTML, not a script. Another way around it is to do something like this:

document.body.appendChild('<script>alert("hi");</' + 'script>');

Here are some resources on this topic:

Sign up to request clarification or add additional context in comments.

Comments

0

I found a way with no need to append nor the createElement methods. I've managed to do it in this manner: html part:

<script id="jsScriptInHtml" data-cfasync="false" type="text/javascript"></script>

js external file:

let logScript = `console.log('ok')`;
document.getElementById("jsScriptInHtml").innerHTML= logScript;

Comments

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.