我正在创建一个书签,一切都很顺利。我有一个函数,如果页面没有它,则加载jQuery异步,然后加载我的脚本或直接加载我的脚本,如果页面有jQuery。
然后我尝试使用仅在jQuery 1.4.something中可用的委托函数。我可以用$().jquery
检查jQuery版本但是如果我加载jQuery我有两次jQuery并且事件执行两次。
有没有办法删除以前加载的jQuery,然后加载我需要的新版本?
答案 0 :(得分:1)
有,但是当你这样做时你会破坏页面,所以我高度建议不要这样做。删除jQuery本身:
jQuery.noConflict(true);
这只是为了表明它可以完成(虽然它没有删除它拥有的所有效果),在你的情况下我不会这样做,是什么你正在做的将真正打破你的书签运行的网页。
相反,考虑一下您的书签是否需要最新的jQuery API,后面的版本是否适合您的所有需求?如果是这样,那么使用它,即使效率稍低,所以无论页面是否有稍旧的版本,它都可以使用。
答案 1 :(得分:1)
可以将jQuery移动到另一个名称空间。
//Completely move jQuery to a new namespace in another object.
var dom = {};
dom.query = jQuery.noConflict(true);
以下是来自另一个question的稍微改动的代码,提问者能够使用与您完全相同的用途(书签)。
/* I have attempted to change the code to check for the 1.4.x and if its not then
load the latest version of jQUery. */
(function(){
var myBkl = {
jq: null,
loadScript: function(src) {
if(window.jQuery && window.jQuery.fn.jquery.indexOf('1.4') >= 0){
return;
}
var s = document.createElement('script');
s.setAttribute('src', src);
s.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
},
whenLoaded: function(callback){
if (typeof(window.jQuery) !== 'undefined' && window.jQuery.fn.jquery.indexOf('1.4') >= 0) {
myBkl.jq = window.jQuery.noConflict(true);
callback(myBkl.jq);
}
else {
setTimeout((function() {myBkl.whenLoaded(callback); }), 100);
}
},
init: function($){
console.log($.fn.jquery);
console.log(window.jQuery.fn.jquery);
}
};
myBkl.loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'); //this will load the latest version from google cdn
myBkl.whenLoaded(myBkl.init);
})();
原始来源参考:Is it possible to load multiple different version of jQuery on the same page?
如果你必须这样做的另一个选择,(在发现你不能像其他人所建议的那样在没有.delgate()
的情况下重写你的书签之后),可以在同一页面上拥有多个版本的jQuery。看下面:
if (typeof jQuery == ‘undefined’) {
appendLatestJQuery();
}
else {
jQVersion = $().jquery;
versionArray = jQVersion.split(‘.’);
if (versionArray[1] < 4) {
appendLatestJQuery();
}
else {
runthis();
}
}
function appendLatestJQuery() {
var jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.onload=runthis;
jQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
document.body.appendChild(jQ);
}
function runthis() {
var $j = jQuery.noConflict(true);
//now use $j for your code here
}