通过jQuery添加的脚本标签在FireBug中不可见 [英] Script tags added via jQuery not visible in FireBug

查看:116
本文介绍了通过jQuery添加的脚本标签在FireBug中不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过jQuery将< script type =text / javascriptsrc =http://somedomain/somescript.js> 添加到文档头。这是我使用的代码:

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

虽然脚本似乎工作正常,但我使用的时候看不到脚本FireBug检查文件头。此片段不显示添加的脚本:

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

这是正常的还是我在这里做错事?令我困扰的是,我看到头部中的其他脚本是懒惰/动态加载的,但不是我添加的。另外想知道是否可以在文档就绪功能中加载操纵DOM的脚本。

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.

代码来自:

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

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

修复了问题。结果DOM在FireBug中正确显示,jQuery正确地返回静态/动态添加的脚本标签。

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

推荐答案

jQuery.com上的此提示

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.

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

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

这篇关于通过jQuery添加的脚本标签在FireBug中不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆