Reputation: 15706
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
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
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
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
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