通过innerHTML工作将脚本插入div,但无法加载

时间:2019-01-03 16:06:13

标签: javascript

我正在通过javascript在div上插入脚本标签。

脚本正在div上加载,但未加载。我假设评估上出了点问题。您可以检查为什么它不起作用吗?

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>

2 个答案:

答案 0 :(得分:2)

外部脚本中没有innerText。同样,innerHTML无法呈现脚本

您可能想这样做:

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>

答案 1 :(得分:1)

下面的代码应使您了解如何实现此目的:

//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>