views:

141

answers:

2

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?

+2  A: 

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

thephpdeveloper
Awesome, thanks!
Ivan
no problem Ivan!
thephpdeveloper
Actually, not so fast. The whole page gets replaced by the remote script. Do you think this has something to do with the remote script itself (this doesn't happen when including it as a plain <script src="..."> tag), or is this avoidable? Also, it doesn't load a remote script :(
Ivan
My mistake, it does load a script from a different domain. But the other issue remains.
Ivan
works well for me. I'll post up the test I did.
thephpdeveloper
var __h = __d.getElementsByTagName("head").item(0);Might be __d.getElementsByTagName("head")[0] instead?
CodeJoust
@CodeJoust - either way works? I'll update the code with yours =)
thephpdeveloper
@CodeJoust - partly because I work on PHP more, and PHP doesn support something like func()[0].
thephpdeveloper
Mmmh, it must be the script then. It loads a Flash movie with <embed>, but I'm not sure why it replaces the whole page.
Ivan
if the script actually `document.write`, then it'll fail.
thephpdeveloper
Ah, that's the issue then. The script does use document.write... I guess I'll have to use a local copy without document.write.
Ivan
A: 

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://...');
Ivan