如果您在页面中包含 2 个版本的 jQuery,您如何将插件限制为其中一个?
所以这个问题并不像一开始听起来那么疯狂.我正在开发一段 javascript 代码以放入我的客户页面.我担心的是他们是否在他们的网站上使用了另一个版本的 jQuery.
So this question isn't as crazy as it might sound at first. I'm developing a piece of javascript code to drop into my client's pages. What I'm worried about is if they are using another version of jQuery on their site.
我从 Jquery docs 知道这样的东西应该可以工作.
I know from the Jquery docs that something like this should work.
var dom = {};
dom.query = jQuery.noConflict(true);
问题是我也在使用一些 jquery 插件,即 fancybox 和 鼠标滚轮.那么如何确保我的 jQuery 版本是唯一可以使用这些插件的版本.如果我们的一位客户碰巧在他们的页面中使用相同的但不同的版本,我不希望发生冲突.
The problem is I am also using some jquery plugins, namely fancybox and mousewheel. So how can I make sure my version of jQuery is the only one that can use those plugins. I don't want a conflict to happen if one of our clients happens to use the same ones in their pages but different versions.
我现在能想到的唯一确定的方法是修改插件,使它们只调用 dom.query
The only definite way I can think of right now is to modify the plugins so they only call dom.query
推荐答案
你可以使用一个技巧.如果您的 jQuery 版本是第二个加载的版本,您需要在加载它之前先移动到安全的版本,就像这样
There is a trick you could use. If your version of jQuery is second which loads, you will need first move to safety theirs version before you load it, something like this
<script type="text/javascript">
(function($){
var theirs_jquery = $;
})(jQuery);
</script>
然后添加你的 jQuery 版本脚本包含标签
Then add your jQuery version script include tag
<script src="link/to/my/jquery.js"></script>
<!-- add your plugins -->
<script src="link/to/my/jquery/plugins/plugin1.js"></script>
<script src="link/to/my/jquery/plugins/plugin2.js"></script>
然后添加另一个脚本块,如下所示
then add another script block with folowing
<script type="text/javascript">
(function(){
var $$ = jQuery; // this is your shortcut
var $ = theirs_jquery; // put back their version
})(jQuery);
</script>
在此之后,您可以使用 $$ 快捷方式访问您的 jquery 版本
after this you can access your jquery version with $$ shortcut
相关文章