John Baber-Lucero
John Baber-Lucero

Reputation: 2652

Why is inserting a script in head with jQuery so strange?

If I confirm I've already got jQuery,

$('<script type="text/javascript"/>').text("alert('boo');").appendTo($("head"));

works as expected. But there's no way to see the script in firebug or Chrome's dev tool.

Nobody recommends inserting a script that way and everyone says to

headtag=document.getElementsByTagName('head')[0];
scripttag=document.createElement('script');
scripttag.type='text/javascript';
scripttag.innerHTML="alert('boo');";
headtag.appendChild(scripttag);

In that case, it is visible in firebug. Why is the latter preferable to the former? Why doesn't firebug show the script?

Upvotes: 1

Views: 81

Answers (1)

Pointy
Pointy

Reputation: 413720

When jQuery deals with HTML text to be appended to the DOM, it always strips out <script> content first. It evaluates the script after updating the DOM.

Upvotes: 4

Related Questions