最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Eval or load a remote script several times - Stack Overflow

programmeradmin2浏览0评论

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

That 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?

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

That 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?

Share Improve this question asked Nov 4, 2009 at 3:21 IvanIvan 104k17 gold badges53 silver badges59 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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

  1. 暂无评论