加载多个jQuery版本

时间:2013-03-01 17:30:07

标签: javascript jquery ajax

我编写了一个使用jQuery的工具,该工具可以动态加载到许多不同的网页上,包括那些已经使用过jQuery的网页。我试图在一个不受我直接控制的网页上加载jQuery。当我这样做时,Ajax调用此页面通过jQuery停止工作。该网站dailycaller.com使用jQuery延迟图像加载 - 当您向下滚动页面时,文章图像是动态加载的。当我尝试加载任何jQuery版本时,此动态图像提取会中断。我怀疑这是由于我加载的jQuery和页面本身已经存在的jQuery之间的版本冲突。

为了测试这个,我尝试加载与页面相同的版本。该页面包含一个脚本标记

<script type='text/javascript' src='http://cdn01.dailycaller.com/wp-includes/js/jquery/jquery.js?ver=1.7.2'></script>

我的JS代码再次加载此版本(在页面加载后异步加载)

var script = document.createElement( 'script' );
script.src = 'http://cdn01.dailycaller.com/wp-includes/js/jquery/jquery.js?ver=1.7.2';
document.body.appendChild(script);

尽管理论上这个版本的jQuery已经在页面上,但这个加载会导致页面的jQuery Ajax调用中断。如何在不破坏此页面动态负载的情况下加载任意jQuery版本?

我已尝试使用Can I use multiple versions of jQuery on the same page?中建议使用的jQuery.noConflict(),但它无法解决此问题。

2 个答案:

答案 0 :(得分:10)

在调用.noConflict()之前,您需要允许动态加载的jQuery副本完成加载。使用onload上的<script>活动。

演示: jsFiddle

脚本:

var script = document.createElement( 'script' );
script.onload = function () {
    jQuery.noConflict( true ); //remove this and image load fails
};
script.src = 'http://cdn01.dailycaller.com/wp-includes/js/jquery/jquery.js?ver=1.7.2';
document.head.appendChild(script);

答案 1 :(得分:4)

我的webapp上有一个非常类似的问题,有一种方法可以保留以前的版本并使用你自己的版本,即使有插件,这就是我的工作:

<!-- USING A NEWER VERSION OF JQUERY -->

<!-- store and protect the old one -->
<script>
var oldJQuery = jQuery.noConflict();
</script>

<!-- load the new version and required plugins -->
<script type="text/javascript" src="../../script/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="../../script/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="../../script/jquery.hammer.js"></script>
<script type="text/javascript" src="../../script/jquery.xml2json.min.js"></script>

<!-- store and protect the new one and put the old one back -->
<script>
var jQuerX = jQuery.noConflict();
jQuery = oldJQuery;
</script>

它保持旧版本不变,您可以在所选别名(jQuerX)下使用您的版本。