Can I create script tag by jQuery?

Viewed 64295

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?

5 Answers

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
}))

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.

Related