4

我编写了一个使用 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 版本?

我已经尝试使用这里推荐的 jQuery.noConflict()我可以在同一页面上使用多个版本的 jQuery 吗?它不能解决这个问题。

4

2 回答 2

10

您需要允许动态加载的 jQuery 副本在调用之前完成加载.noConflict()。在 上使用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);
于 2013-03-01T19:52:31.083 回答
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) 下使用您的。

于 2013-07-01T14:59:32.293 回答