-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);

2 Answers2

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:

ljolz
  • 216
  • 1
  • 3
  • 8
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;