Search code examples
jqueryinvisibleappendto

jQuery $("<script></script>").appendTo("head"); does not show up in GENERATED source code. HOW?


Well, this is not really a problem, but something really interests me.

Normally we append elements to head/body like

$("<style><\/style>").appendTo("head");
$("<div><\/div>").appendTo("body");

And when we look at the generated source code, these elements are really there. but,

$("<script><\/script>").appendTo("head");

The script element does not show up in the source code.

I looked through the source code of jQuery, and didn't find anything special but pure javascript

append: function() {
    return this.domManip(arguments, true, function( elem ) {
        if ( this.nodeType === 1 ) {
            this.appendChild( elem ); // <--
        }
    });
},

If I use pure Javascript to add a script element to head, it'll show up.

So how does jQuery do that to make the script "invisible" and meanwhile "accessible"?
What's special about the script tag?

update: note before you answer

  • I am not trying to solve a problem.
  • I AM using Firebug/Developer tools.
  • I am viewing the GENERATED source code.

Solution

  • This is not singularly related to appendTo as you might first believe. Rather, this is something that jQuery does for all of their functions that insert arbitrary HTML strings into the DOM.

    To see an in-depth answer as to why this happens, read John Resig's reply to this same question here.

    From what I know, jQuery actually removes the script tag after inserting it into the DOM, in order to avoid re-execution of the code.