42

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,417
  • 4
  • 37
  • 60
Billy
  • 14,966
  • 28
  • 69
  • 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,603
  • 2
  • 35
  • 42
  • 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,029
  • 16
  • 78
  • 89
16

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

Lee Taylor
  • 7,155
  • 14
  • 29
  • 44
epascarello
  • 195,511
  • 20
  • 184
  • 225
  • 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
  • 402
  • 5
  • 14