设置
我有一个脚本,该脚本在页面上使用jQuery (True)加载noConflict(true),这些页面上可能已经有一个旧版本的jQuery。我的脚本是在节点中使用模块构建的,并使用browserify打包成一个文件。
问题
我在正确界定其他模块的函数范围以保留通过noConflict()设置的变量$时遇到了问题。例如,假设一个站点已经加载了jQuery版本1.8,而我的脚本已加载到页面上,并加载了jQuery v.3.2
<!-- Client site loads old version of jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
</script>
<!-- Our script loads via ajax as a self executing anonymous function.
Just using this scrip tag as an example -->
<script src="myScript.js"></script>
// Contents of myScript.js is bundled with Browserify and hosted
//on our server. Here is the pre-Browserify code:
var otherModule = require('./funcB')
//check version of jQuery and load newer version if necessary
if ((typeof jQuery === 'undefined') || (parseFloat(jQuery.fn.jquery) < 3.0)) {
//loadScript (not shown) is just a function that adds a script tag via
//ajax to the site <head>
loadScript("https://code.jquery.com/jquery-3.2.1.min.js", function(){
jQuery321 = jQuery.noConflict(true);
funcA(jQuery321);
});
} else {
funcA(jQuery);
}
var funcA = function($){
$('document').ready(function(){
console.log('jquery in funcA: v' + $.fn.jquery)
//outputs: "jquery in funcA: v3.2.1"
otherModule.funcB();
//outputs: "jquery in funcB: v1.8.1"
funcC();
//outputs: "jquery in funcB: v3.2.1"
})
function funcC(){
console.log('jquery in funcC: v' + $.fn.jquery)
}
}
//code from otherModule --> funcB.js
exports.funcB = function(){
console.log("jQuery in funcB: v" + $.fn.jquery)
}
module.exports = exports;
问题--很明显,这个问题和预期的一样,但是,在模块otherModule中是否有一种方法可以将$保留为对jQuery v3.2.1的引用?也许是用布朗赛化变换?
将我的所有模块迁移到funcA中,以便正确地限定函数的作用域,这当然是一个非常棘手的问题,所以如果有办法绕过它,那就太好了。我尝试将我的require语句移到funcA中,我也尝试将$传递到funcB中,但两者都没有工作。
谢谢你的帮忙!
发布于 2018-10-15 23:48:42
谢谢Bergi的小费!它把我引向正确的方向。现在,$ in模块的所有版本为3.2.1,浏览器控制台中的$为1.8.1。
评论指出了新的代码:
var jQuery321; //add variable name for exporting
var otherModule = require('./funcB')
//now we set jQuery321 to the proper version of jQuery to export
if ((typeof jQuery === 'undefined') || (parseFloat(jQuery.fn.jquery) < 3.0)) {
loadScript("https://code.jquery.com/jquery-3.2.1.min.js", function(){
jQuery321 = jQuery.noConflict(true);
funcA(jQuery321);
});
} else {
jQuery321 = jQuery; //added this line
funcA(jQuery);
}
var funcA = function($){
$('document').ready(function(){
console.log('jquery in funcA: v' + $.fn.jquery)
otherModule.funcB();
funcC();
})
function funcC(){
console.log('jquery in funcC: v' + $.fn.jquery)
}
}
export { jQuery321 }; //export proper version of jQuery
//code from otherModule --> funcB.js
import { jQuery321 as $ } from '/myScript.js'; //add import statement
exports.funcB = function(){
console.log("jQuery in funcB: v" + $.fn.jquery)
}
module.exports = exports;
https://stackoverflow.com/questions/52804885
复制相似问题