views:

54

answers:

4

I am adding <script type="text/javascript" src="http://somedomain/somescript.js"&gt; to the document head via jQuery. This is the code I use:

$(document).ready(function () {
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = (document.location.protocol == "https:" ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";
    $("head").append(s);
});

While the script seems to be working perfectly, I do not see the scripts in the head when I use FireBug to inspect document head. This snippet does not show the added script(s) either:

$('script[src]').each(function(){
    console.log(this.src);
});

Is this normal or am I doing something wrong here? What bothers me is the fact that I see other scripts in the head section that were lazy/dynamically loaded but not those that I added. Also wondering if it is OK to load scripts that manipulate DOM in the document ready function.

UPDATE

Replacing the code from:

$("head").append(s);

to

document.getElementsByTagName("head")[0].appendChild(s);

fixes the problem. The resulting DOM appears correctly in FireBug and jQuery correctly returns the script tags that were added static/dynamically.

+1  A: 

You will see a request being made to the script in the NET tab but the script tag won't be visible when inspecting the DOM. This seems like a bug in FireBug.

Darin Dimitrov
Does this mean jQuery won't be able to select the script tags either?
Salman A
A: 

Test it in Chrome as well using the Right-click "Inspect Element" option to use the full debugger (view source will not show the script's modifications). The elements HTML tab should show real-time changes to the DOM

STW
Google Chrome does not show them either :(
Salman A
my mistake, I was thinking of "Inspect Element" in Firefox w/ Firebug. I'm testing it right now on a page with a slideshow, each time the slideshow transitions firebug updated the HTML tab to show the current DOM, and highlights the modified elements for ~1s
STW
A: 

Ok, I found this tip on jQuery.com:

> It should be noted that any attempts to append script elements using this
> method will fail silently:
> $('#element').append("<script></script>");

>> Not exactly. Scripts will be evaluated first, and then discarded.
>> So, if you do this:
>> $('#element').append("<script>alert('hello');</script>");
>> You'll see the alert.

This probably means that the script is evaluated but not inserted in the DOM.

Salman A
+1  A: 

This is a bug in Mozilla's 'jsd' debugger support. One workaround is post on the on the bug cited above:

http://code.google.com/p/fbug/issues/detail?id=1774

If jquery used eval() instead of script tag injection then you could debug this in Firebug.

johnjbarton