43

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 achieve it?

Balder
  • 8,623
  • 4
  • 39
  • 61
Billy
  • 15,516
  • 28
  • 70
  • 101

5 Answers5

69

You should do it like so

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

$("body").append(script);
Cristian Toma
  • 5,662
  • 2
  • 36
  • 43
  • 1
    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 Aug 13 '09 at 16:02
41

To load from a url:

$("body").append($("<script />", {
  src: url
}))

To load from existing source code:

$("body").append($("<script />", {
  html: code
}))
Daniel X Moore
  • 14,637
  • 17
  • 80
  • 92
16

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

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 3
    I want to load another javascript which the javascript is in another domain. – Billy Jul 29 '09 at 12:23
  • 10
    This should be a comment rather than an answer, or it should at least be written as an answer rather than as a question. It's not clearly certain that `getScript()` can do everything that's possible with creating script tags. And if it is, the answer would be much better if it actually stated that. – hippietrail Aug 11 '12 at 08:26
12

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.

2

This can help, who end up here after 8 years

$('<script>alert("hi");</' + 'script>').appendTo(body);

The only reason you can't do $('<script></script>') is because the string isn't allowed inside javascript because the DOM layer can't parse what's js and what's html.

VipinKundal
  • 442
  • 6
  • 14