多次Eval或加载远程脚本

Iva*_*van 1 javascript prototype

是否可以加载远程脚本并对其进行评估?

例如:

$(someelement).update("<script type='text/javascript' src='/otherscript.js'>");
Run Code Online (Sandbox Code Playgroud)

并在otherscript.js:

alert('hi!');
Run Code Online (Sandbox Code Playgroud)

这不起作用.我想在每次用户点击某些内容时加载该脚本.我想另一种选择是将该脚本的内容放在我的主脚本中(并根据需要进行评估),但这不是一个非常好的方法.

此外,如果可以,是否可以从另一个域评估脚本?

mau*_*ris 7

不使用任何框架(感谢CodeJoust):

// a is the script to call
// b is the ID of the script tag (optional)

function scriptc(a,b){
  var __d=document;
  var __h = __d.getElementsByTagName("head")[0];
  var s = __d.createElement("script");
  s.setAttribute("src", a);
  s.id = b;
  __h.appendChild(s);
}

scriptc("http://example.com/someother.js");
// adds to DOM and it'll get loaded
Run Code Online (Sandbox Code Playgroud)

但请注意,因为其他域上的脚本可以访问您域中的敏感信息,例如PHP中的Cookie会话ID.

例:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<div id="cool">testing</div>

<script type="text/javascript">//<!--
function scriptc(a,b){
  var __d=document;
  var __h = __d.getElementsByTagName("head").item(0);
  var s = __d.createElement("script");
  s.setAttribute("src", a);
  s.id = b;
  __h.appendChild(s);
}

scriptc("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js");

// --></script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

加载之后,我使用Firebug进行检查$("#cool").html().