通过jQuery添加的脚本标记在FireBug中不可见

我通过jQuery将到文档头。 这是我使用的代码:

 $(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); }); 

虽然脚本似乎运行得很好,但是当我使用FireBug检查文档头时,我看不到头部中的脚本。 此代码段不会显示添加的脚本:

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

这是正常的还是我在这里做错了什么? 困扰我的是,我在head部分看到其他脚本是懒惰/动态加载但不是我添加的那些脚本。 还想知道在文档就绪函数中加载操作DOM的脚本是否可以。

UPDATE

替换代码:

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

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

解决了这个问题。 生成的DOM在FireBug中正确显示,jQuery正确返回静态/动态添加的脚本标记。

您将在NET选项卡中看到对脚本发出的请求,但在检查DOM时, script标记将不可见。 这似乎是FireBug中的一个错误 。

这是Mozilla的’jsd’调试器支持中的一个错误。 一个解决方法是发布上面引用的bug:

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

如果jquery使用eval()而不是脚本标记注入,那么你可以在Firebug中调试它。

好的,我在jQuery.com上发现了这个提示 :

 > It should be noted that any attempts to append script elements using this > method will fail silently: > $('#element').append(""); >> Not exactly. Scripts will be evaluated first, and then discarded. >> So, if you do this: >> $('#element').append(""); >> You'll see the alert. 

这可能意味着脚本已经过评估但未插入DOM中。

使用右键单击“Inspect Element”选项在Chrome中测试它以使用完整的调试器(视图源不会显示脚本的修改)。 元素 HTML选项卡应显示DOM的实时更改