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?

3
  • I'm just interested: why would you do that? You're already running JavaScript code, so why do you need another block? Commented Jul 29, 2009 at 11:48
  • 7
    stackoverflow.com/questions/610995/… Commented Jul 29, 2009 at 11:50
  • 4
    I want to load another javascript file after loading the page. Commented Jul 29, 2009 at 11:59

5 Answers 5

69

You should do it like so

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

$("body").append(script);
Sign up to request clarification or add additional context in comments.

1 Comment

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
41

To load from a url:

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

To load from existing source code:

$("body").append($("<script />", {
  html: code
}))

Comments

16

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

2 Comments

I want to load another javascript which the javascript is in another domain.
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.
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.