gpt4 book ai didi

javascript - 以编程方式在高度冲突的环境中包含 JQuery -

转载 作者:行者123 更新时间:2023-12-01 02:04:50 25 4
gpt4 key购买 nike

我正在编写一段代码,将其放在任何第三方网站上,但不知道它将被放入什么环境中。我的最终目标是徽章

<script src="http://example.com/js/badge.js"></script>

我想在我的徽章代码中使用 jQuery 来让我的生活更轻松,但我不想在客户端要求另一个包含(在客户端更新任何内容都是一件痛苦的事情)。

这是我能想到的最好的办法了。我不希望我的脚本之前或之后的任何内容受到任何剩余变量或奇怪的冲突的影响。有人发现任何问题吗?

(function() {
function main($) {
// do stuff with $
$(document.body).css("background", "black")
}

// If jQuery exists, save it
var old_jQuery = null;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery.noConflict(true);
}
}

var addLibs = function() {
// Body isn't loaded yet
if (typeof(document.body) == "undefined" || document.body === null) {
setTimeout(addLibs, 100);
return;
}

var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
document.body.appendChild(node);
checkLibs();
}

var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || jQuery("*") === null) {
setTimeout(checkLibs, 100);
return;
}
var new_jQuery = jQuery.noConflict(true);
jQuery = old_jQuery;
main(new_jQuery);
}

addLibs();
})();

最佳答案

我最终选择了 http://yourock.paulisageek.com/js/popup.js 。查看测试(可使用控制台日志记录)http://paulisageek.com/tmp/jquery-programatically.html 。在 jQuery 实际完成加载之前,它不会重置 jQuery 和 $。有什么方法可以阻止 javascript 而不产生无限循环(这会阻止 jQuery 加载本身)?

// A namespace for all the internal code
var yourock = {};

// Include JQuery programatically
(function() {
// Don't let the script run forever
var attempts = 30;

// If jQuery exists, save it and delete it to know when mine is loaded
var old_jQuery;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery;
delete jQuery;
}
}

var addLibs = function() {
var head = document.getElementsByTagName("head");
if (head.length == 0) {
if (attempts-- > 0) setTimeout(addLibs, 100);
return;
}

var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
head[0].appendChild(node);
checkLibs();
}

var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || typeof(jQuery) != "function" || jQuery("*") === null) {
if (attempts-- > 0) setTimeout(checkLibs, 100);
return;
}
yourock.jQuery = jQuery.noConflict(true);
if (typeof old_jQuery == "undefined")
jQuery = old_jQuery;
}

addLibs();
})();

关于javascript - 以编程方式在高度冲突的环境中包含 JQuery -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1005600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com