Can I create script tag by jQuery?

You should do it like so

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

$("body").append(script);

To load from a url:

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

To load from existing source code:

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

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


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.


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.