Alex Rivera | Logout

Can I create script tag by jQuery?

Asked 2009-07-29T11:45:03.317
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?

Edit
Report

3 Answers

41

To load from a url:

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

To load from existing source code:

$("body").append($("<script />", {
  html: code
}))
answered 2011-02-11T23:21:12.643
16

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

answered 2009-07-29T11:56:57.763
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.

answered 2009-07-29T11:48:45.257

Your Answer