Billy
Billy

Reputation: 15706

Can I create script tag by jQuery?

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?

Upvotes: 43

Views: 67146

Answers (5)

epascarello
epascarello

Reputation: 207501

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

Upvotes: 16

VipinKundal
VipinKundal

Reputation: 460

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.

Upvotes: 2

Daniel X Moore
Daniel X Moore

Reputation: 15060

To load from a url:

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

To load from existing source code:

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

Upvotes: 41

Cristian Toma
Cristian Toma

Reputation: 5799

You should do it like so

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

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

Upvotes: 69

user434917
user434917

Reputation:

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.

Upvotes: 12

Related Questions