views:

1025

answers:

3

I want to create a script tag by jQuery.

I use the following code:

$("<body>").append("<script></script>");

It doesn't work. What will you do to acheive it?

+5  A: 

You should do it like so

var script=document.createElement('script');
script.type='text/javascript';
script.src=url;

$("body").append(script);
Christian Toma
I have tested this code and it works.Thanks.
Billy
You're welcome Billy.
Christian Toma
sounds like an accepted answer is coming?
geowa4
Why use this when jQuery provides $.getScript???
J-P
Read Billy's comment below.
Christian Toma
@Christian, getScript works with external hosts!
J-P
Can I ask why would you not use a jQuery based solution when you are using jQuery? getScript will work, you should try it. lol
epascarello
+2  A: 

The error is in the selector:

$("body").append("<script>alert('hello world');<\/script>");

Note that you have to escape the unallowed characters in the appended string.

Marwan Aouida
+3  A: 

Why are you not using jQuery.getScript(url,[callback])

epascarello
I want to load another javascript which the javascript is in another domain.
Billy
getScript will still work...
J-P