代码之家  ›  专栏  ›  技术社区  ›  Salman Arshad

通过jquery添加的脚本标记在Firebug中不可见

  •  8
  • Salman Arshad  · 技术社区  · 14 年前

    我在加 <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);
    });
    

    虽然脚本看起来工作得很好,但是当我使用Firebug检查文档头时,我看不到头部中的脚本。此代码段也不显示添加的脚本:

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

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

    更新

    将代码替换为:

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

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

    解决了问题。生成的dom正确地出现在firebug中,jquery正确地返回添加了静态/动态的脚本标记。

    4 回复  |  直到 12 年前
        1
  •  1
  •   Darin Dimitrov    14 年前

    您将看到在 NET 但标签 script 检查DOM时,标记将不可见。这好像是 bug 在萤火虫中。

        2
  •  1
  •   johnjbarton    14 年前

    这是Mozilla的“JSD”调试器支持中的一个bug。一个解决方法是发布在上面引用的bug上:

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

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

        3
  •  1
  •   Salman Arshad    12 年前

    好的,我找到了 this tip 关于JQueYu.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.
    

    这可能意味着对脚本进行了计算,但没有将其插入到DOM中。

        4
  •  0
  •   STW    14 年前

    也可以用铬来测试 使用右键单击“inspect element”选项使用完整的调试器(视图源不会显示脚本的修改)。这个 元素 HTML选项卡应显示对DOM的实时更改