我可以在同一页面上使用多个版本的 jQuery 吗?

问题描述:

我正在处理的一个项目需要在客户的网页上使用 jQuery.客户将插入我们将提供的一段代码,其中包括一些 元素,这些元素在 创建的 中构建小部件.如果他们还没有使用最新版本的 jQuery,这也将包括(很可能)一个 <script> 用于 Google 托管的 jQuery 版本.

A project I'm working on requires the use of jQuery on customers' Web pages. Customers will insert a chunk of code that we'll supply which includes a few <script> elements that build a widget in a <script>-created <iframe>. If they aren't already using the latest version of jQuery, this will also include (most likely) a <script> for Google's hosted version of jQuery.

问题是一些客户可能已经安装了旧版本的 jQuery.虽然如果它至少是一个相当新的版本,这可能会起作用,但我们的代码确实依赖于 jQuery 库中最近引入的一些功能,因此肯定会出现客户的 jQuery 版本太旧的情况.我们不能要求他们升级到最新版本的 jQuery.

The problem is that some customers may already have an older version of jQuery installed. While this may work if it's at least a fairly recent version, our code does rely on some recently introduced functionality in the jQuery library, so there are bound to be instances when a customer's jQuery version is just too old. We can't require that they upgrade to the latest version of jQuery.

有什么方法可以加载较新版本的 jQuery 以仅在我们的代码上下文中使用,而不会干扰或影响客户页面上的任何代码?理想情况下,也许我们可以检查 jQuery 是否存在,检测版本,如果它太旧,然后以某种方式加载最新版本以用于我们的代码.

Is there any way to load a newer version of jQuery to use only within the context of our code, that will not interfere with, or affect, any code on the customer's page? Ideally, maybe we could check for the presence of jQuery, detect the version, and if it's too old, then somehow load the most recent version just to use for our code.

我有在客户域中的 中加载 jQuery 的想法,该域还包括我们的 ,这似乎是可行的,但我希望有一种更优雅的方式来做到这一点(更不用说没有额外 的性能和复杂性损失).

I had the idea of loading jQuery in an <iframe> in the customer's domain that also includes our <script>, which seems like it might be feasible, but I'm hoping there's a more elegant way to do it (not to mention without the performance and complexity penalties of extra <iframe>s).

是的,由于 jQuery 的无冲突模式,这是可行的.http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/

Yes, it's doable due to jQuery's noconflict mode. http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/

<!-- load jQuery 1.1.3 -->
<script type="text/javascript" src="http://example.com/jquery-1.1.3.js"></script>
<script type="text/javascript">
var jQuery_1_1_3 = $.noConflict(true);
</script>

<!-- load jQuery 1.3.2 -->
<script type="text/javascript" src="http://example.com/jquery-1.3.2.js"></script>
<script type="text/javascript">
var jQuery_1_3_2 = $.noConflict(true);
</script>

然后,代替 $('#selector').function();,你会做 jQuery_1_3_2('#selector').function();jQuery_1_1_3('#selector').function();.

Then, instead of $('#selector').function();, you'd do jQuery_1_3_2('#selector').function(); or jQuery_1_1_3('#selector').function();.