I am adding <script type="text/javascript" src="http://somedomain/somescript.js"> 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.
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.
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.
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.
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
来源:https://stackoverflow.com/questions/3075609/script-tags-added-via-jquery-not-visible-in-firebug