Bookmarklet中有多个jQ.src

时间:2011-05-16 04:47:11

标签: javascript bookmarklet

这是我当前的bookmarklet代码。

if (1 == 1) {
    var jQ = document.createElement('script');
    jQ.type = 'text/javascript';
    jQ.onload=runthis;
    jQ.src = 'http://www.domain.com/jquery-1.5.2.min.js';
    document.head.appendChild(jQ);
}

我想调用多个jQ.src。我试过这个,但它在某些网站上不起作用。

这是我当前的bookmarklet代码。

if (1 == 1) {
    var jQ = document.createElement('script');
    jQ.type = 'text/javascript';
    jQ.onload=runthis;
    jQ.src = 'http://www.domain.com/jquery.js';
        jQ.src = 'http://www.domain.com/jquery2.js';
    document.head.appendChild(jQ);
}

在某些网站上它可以运作,而其他网站没有任何洞察力?

谢谢!

1 个答案:

答案 0 :(得分:1)

您确定在某些网站上有效吗?我觉得你很幸运,拿起网站已经加载的jQuery。

无论如何,如果你想添加两个JavaScript文件,那么你必须附加两个脚本标签:

var jQ  = document.createElement('script');
jQ.type = 'text/javascript';
jQ.src  = 'http://www.domain.com/jquery.js';
document.head.appendChild(jQ);

jQ        = document.createElement('script');
jQ.type   = 'text/javascript';
jQ.src    = 'http://www.domain.com/jquery2.js';
jQ.onload = runthis;
document.head.appendChild(jQ);

另请注意,onload仅在第二个上,因为您可能需要在runthis之前加载两个JavaScript文件。

如果你正在加载jQuery,你可能想检查页面是否已经加载了它:

var jQ;
if(typeof window.jQuery != 'function') {
    // jQuery isn't there yet so load it up.
    jQ      = document.createElement('script');
    jQ.type = 'text/javascript';
    jQ.src  = 'http://www.domain.com/jquery.js';
    document.head.appendChild(jQ);
}
jQ        = document.createElement('script');
jQ.type   = 'text/javascript';
jQ.src    = 'http://www.domain.com/jQuery2.js';
jQ.onload = runthis;
document.head.appendChild(jQ);

添加jQuery.noConflict()调用可能也是一个好主意,该页面可能正在使用$进行其他操作,因此强制它成为jQuery可能会破坏页面。