开发者

Eval or load a remote script several times

Is it possible to load a remote script and have it eval'ed?

For example:

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

And in otherscript.js:

alert('hi!');

T开发者_开发知识库hat doesn't work. I want to load that script each time the user clicks something. I guess another option would be to put the contents of that script in my main script (and eval it as needed), but that's not a very good approach.

Also, if this is possible, would it be possible to eval a script from another domain too?


Without using any framework (with thanks to 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

However take caution because the script on other domains can access sensitive information on your domain, such as the Session ID through cookies in PHP.

Example:

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

After which is loaded, I use Firebug to examine $("#cool").html().


This is the Prototype way in case anyone finds it helpful:

function scriptc(parent, src) {
  var s = new Element('script');
  parent.appendChild(s);
}

scriptc($('someelement'), 'http://...');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜