gpt4 book ai didi

jquery - 如何让两个 chrome 用户脚本仅使用一个 jQuery 实例?

转载 作者:行者123 更新时间:2023-12-01 05:00:53 25 4
gpt4 key购买 nike

在我的用户脚本中,我使用此代码来注入(inject)和执行 jQuery 和其余代码:

function addJQuery(callback) {
var script = document.createElement("script");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
script.addEventListener('load', function() {
var script = document.createElement("script");
script.textContent = "(" + callback.toString() + ")();";
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
}
function readyJQuery() {
jQuery.noConflict();
jQuery(document).ready(function() {
//my rest code goes here
})
}
addJQuery(readyJQuery)


这非常有效。但是当我有两个脚本时,它们都注入(inject) jQuery 部分。这些脚本需要分开,因为我不知道谁想使用哪个脚本或两个脚本。

我可以阻止第二个脚本注入(inject) jQuery 并使用第一个脚本中的脚本吗?

当第二个脚本直接开头时:

function addJQuery(callback) {
var script = document.createElement("script");
script.textContent = "(" + callback.toString() + ")();";
document.body.appendChild(script);
}
function readyJQuery() {
jQuery.noConflict();
jQuery(document).ready(function() {
//my rest code goes here
})
}
addJQuery(readyJQuery)

我在控制台中收到错误消息:jQuery 未定义。如何测试不同的脚本是否已注入(inject) jQuery,然后等待它准备好?

最佳答案

给你的 jQuery 一个唯一的标识符,检查该标识符,并且仅在找不到时添加 jQuery。您还需要留出足够的时间来初始化第一个 jQuery。

在两个脚本中将 addJQuery() 更改为以下内容,在我的测试中有效:

function addJQuery (callback) {
//--- Has jQuery already been added?
var jqNode = document.querySelector ("#myAddedJQ");
if (jqNode) {
FireCallback (callback);
}
else {
//--- Wait a bit to be sure.
setTimeout ( function() {
var jqNode = document.querySelector ("#myAddedJQ");
if (jqNode) {
FireCallback (callback);
}
else {
var script = document.createElement ("script");
script.id = "myAddedJQ";
script.setAttribute (
"src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
);
script.addEventListener ('load', function () {
FireCallback (callback);
}, false);
document.body.appendChild (script);
}
}
, 444
);
}

function FireCallback (callback) {
var script = document.createElement ("script");
script.textContent = " \
if (typeof waitForJqDefined == 'undefined') { \
var waitForJqDefined = setInterval ( function () { \
if (typeof jQuery != 'undefined') { \
clearInterval (waitForJqDefined); \
";
script.textContent += "\n(" + callback.toString() + ")();\n";
script.textContent += " \
} \
}, \
50 \
); \
} \
else { \
";
script.textContent += "\n(" + callback.toString() + ")();\n";
script.textContent += " \
} \
";
document.body.appendChild (script);
}
}

关于jquery - 如何让两个 chrome 用户脚本仅使用一个 jQuery 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10256095/

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