Rasel Ahmed
Rasel Ahmed

Reputation: 305

Insert script to a div via innerHTML working but not loading

I am inserting a script tag on a div by javascript.

The script is loading on div but it is not loading. I am assuming something going wrong on eval. Can you check why it is not working?

var mydiv = document.getElementById("mydiv");
var content = "<script src='https://gist.github.com/raselahmed7/e233c308d5bf354c9d174f80a30c6b6a.js'><\/script>";

mydiv.innerHTML = content;
var scripts = mydiv.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
  eval(scripts[i].innerText);
}
<div id="mydiv"></div>

Upvotes: 0

Views: 642

Answers (2)

Daniel Black
Daniel Black

Reputation: 605

The below code should give you an idea on how this can be accomplished:

//attach click event listeners
document.getElementById("loadButton").addEventListener("click", loadScript);
document.getElementById("testButton").addEventListener("click", testScript);

//this function should only work after the script has been loaded
function testScript(){
	$('#title').text('Used the loaded script!');
}

//this function will append the created script element to the head
function loadScript() {
  var script = document.createElement('script');

  script.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js');

  document.head.appendChild(script);
}
<html>

  <head>
    <title>
      Testing Dynamic Scripts
    </title>
  </head>

  <body>
    <h1 id="title">
      Testing Dynamic Scripts
    </h1>
    <div>
      <input id="loadButton" type="button" value="Load Script" />
      <input id="testButton" type="button" value="Test Script" />
    </div>
  </body>

</html>

Upvotes: 1

mplungjan
mplungjan

Reputation: 177702

There is no innerText in an external script. Also innerHTML does not render scripts

You likely want to do this:

var myDiv = document.getElementById("mydiv");
var oldWrite = document.write, html=[];
document.write = function(str) {
  html.push(str);
}
var script = document.createElement("script");
script.src="https://gist.github.com/raselahmed7/e233c308d5bf354c9d174f80a30c6b6a.js"
document.getElementsByTagName("head")[0].appendChild(script)
setTimeout(function() { myDiv.innerHTML=html.join("\n") },1000)
<div id="mydiv"></div>

Upvotes: 2

Related Questions