是否可以在同一页面上使用jQuery的2个版本?

问题描述:

注意:我知道已经问过类似的问题了在这里,但是我正在寻找其他说明,以了解如何使它起作用,或者是完全避免使用它的充分理由.

NOTE: I know similar questions have already been asked here and here, but I'm looking for additional clarification as to how to make this work or good reasons for avoiding it entirely.

我正在向已经使用旧版本jQuery库(1.1.3.1)的现有网站添加功能.我一直在针对最新版本的jQuery库(1.4.2)编写添加的功能.我仅使用较新版本的jQuery测试了该网站,但它破坏了功能,因此现在我打算在同一页面上使用这两个版本.这怎么可能?

I'm adding functionality to an existing web site that is already using an older version of the jQuery library (1.1.3.1). I've been writing my added functionality against the newest version of the jQuery library (1.4.2). I've tested the website using only the newer version of jQuery and it breaks functionality, so now I'm looking at using both versions on the same page. How is this possible?

我需要在代码中做什么以指定我使用的是一个版本的jQuery,而不是另一个版本的?例如,我将两个版本的jQuery的<script>标记放在页面的标题中,但是我需要做些什么,以便使我在调用代码中确定知道正在调用该库的一个版本还是另一个?

What do I need to do in my code to specify that I'm using one version of jQuery instead of another? For example, I'll put <script> tags for both versions of jQuery in the header of my page, but what do I need to do so that I know for sure in my calling code that I'm calling one version of the library or another?

也许是这样的:

//Put some code here to specify a variable that will be using the newer
//version of jquery:
var $NEW = jQuery.theNewestVersion();

//Now when I use $NEW, I'll know it's the newest version and won't
//conflict with the older version.
$NEW('#personName').text('Ben');

//And when I use the original $ in code, or simply 'jquery', I'll know
//it's the older version.
$('#personName').doSomethingWithTheOlderVersion();

更新:阅读了一些答案之后,我开始怀疑尝试玩这个游戏是否甚至是个好主意...

可能?是的,就像可以同时运行jQuery和另一个使用名称$的框架一样.包括一个jQuery副本,并使用noConflict将其分配给新名称,然后对另一个副本进行相同的操作.

Possible? Yes, in the same way that it's possible to run jQuery and another framework that uses the name $ at the same time. Include one copy of jQuery and assign it to a new name using noConflict, then do the same to another copy.

一个好主意?真的,就像同时运行jQuery和另一个框架不是一个好主意一样,更多的是. jQuery是一个影响深远的侵入性框架.如果jQuery的两个实例开始变异相同的元素(并且1.4之前的jQuery版本对于它们接触的元素非常混杂),则它们很可能彼此混淆,具有不可预测的,对时间敏感的和不可容忍的副作用.

A good idea? Really no, in the same way that running jQuery and another framework at the same time isn't a good idea, only more so. jQuery is a far-reaching, invasive framework. If two instances of jQuery start mutating the same element (and versions of jQuery before 1.4 are very promiscuous about what elements they touch), they are likely to confuse each other with unpredictable, timing-sensitive and undebuggable side-effects.

如果可能的话,更新所有代码以在最新的jQuery下运行是最好的方法.这确实不应该那么困难. jQuery开发人员并没有过多破坏代码本来应该依赖的地方.

If at all possible, updating all the code to run under the latest jQuery is by far the better route. This really shouldn't be that difficult; the jQuery devs haven't broken much that code should ever have relied on in the first place.