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

Sal*_*n A 8 javascript debugging jquery firebug

<script type="text/javascript" src="http://somedomain/somescript.js">通过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);
});
Run Code Online (Sandbox Code Playgroud)

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

$('script[src]').each(function(){
    console.log(this.src);
});
Run Code Online (Sandbox Code Playgroud)

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

UPDATE

替换代码:

$("head").append(s);
Run Code Online (Sandbox Code Playgroud)

document.getElementsByTagName("head")[0].appendChild(s);
Run Code Online (Sandbox Code Playgroud)

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

Sal*_*n A 1

好的,我在 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.
Run Code Online (Sandbox Code Playgroud)

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