我有一个 javascript 库,可以在不同类型的网站上运行,例如 wordpress 或 magento。 js lib 动态加载 jQuery 并调用 noConflict 来分配给脚本元素的 onereadystatechange() 中的另一个变量命名空间。但是,如果该网站还在我的 js 库之前加载 Prototype js,则 Prototype 和 jQuery 之间可能会发生冲突。
在调用 onereadystatechange 回调之前,可能会解析页面并可能调用 Prototype 函数。如果该 Prototype 函数使用任何“$”,则会导致该函数失败,因为该美元符号“$”仍然是 jQuery,而不是 Prototype(在调用 jQuery.noConflict() 之前)。
我可以构建一个自定义 jQuery 来完全不使用“$”,这样就不需要因为上述原因再次加载 Prototype 了吗?
EDIT 1:
以下是我的 js 库 (mylib.js) 在网站上使用的过程,以及 jQuery 可能如何与该网站的 Prototype 发生冲突。
onepage.html 来自其他人的网站
<head>
<script src="prototype.js" type="text/javascript"></script>
<script src="mylib.js" type="text/javascript"></script>
</head>
mylib.js
1. If jQuery is not defined, create a script element with jQuery src and insert to header.
2. In the script element, attach event onreadystatechange.
element.attachEvent('onreadystatechange', function () {
if (elem.readyState == 'loaded' || elem.readyState == 'complete') {
callback();
}
});
3. in callback(), I called noConflict().
var callback = function() {
return function() {
if (window['jQuery'] && hasJQueryReqVersion()) {
window.myJQ = jQuery.noConflict(true);
}
}
}();
问题是在调用callback()之前,可能会调用Prototype,并且它会意外地使用已被jQuery覆盖的“$”。