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?

Answers:

Answer

To load from a url:

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

To load from existing source code:

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

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

Answer

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.

Answer

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.

Answer

You should do it like so

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.