原文:Better, Stronger, Safer jQuerify Bookmarklet作者:Karl Swedberg
老早以前,我自己写了个书签来给没有引入Jquery的页面动态引入Jquery库。这个想法可以让我在所有的页面中都使用Jquery和Firebug(现在也包括safari和IE8)控制台。我写了篇博客,得到不少反馈,然后又发了个高级版。看着那么多的评论不断跟新,我也就想着在把它更新一次。
下面是这个书签
要想使用这个书签,只需要简单地把下面的链接托进你的收藏夹里面:
» jQuerify «
当你想在一个没有包含Jquery的网页中玩Jquery的时候,只需要点一下这个书签就可以了。
前面版本存在的问题
以前版本最大的问题就是当遇到其他使用$标记的库已经引入进页面时,比如说Prototype和Mootools,这个书签就不起作用了。许多人评论建议我在代码中加行jQuery.noConflict();但是我不怎么想使用jQuery()来代替$()。
第二个问题,在测试新版本的时候我发现,可能是我通过Google CDN引入的jQuery不能在我想用它的时候及时的加载进来,所以这时候就会出现”jQuery is not defined” 的错误。
新版本的改进
为了解决这个问题,我让这段代码做了些不同的事情:
- 加了个计数器,在放弃加载前检查十次,看看jQuery究竟有没有成功载入
- 在每次检查之间设置250ms的延时
- 检查$()函数是否已经被其他库给使用了,如果已经被使用:
- 使用jQuery的 $.noConflict来代替$()
- 为了方便把$jq设置为jQuery的别名
- 提示jQuery和其他有冲突,要使用$jq()来代替$()
- 如果重复多次还不能够加载jQuery,那么就显示提示信息,并放弃使用jQuery而是使用javascript
下面的代码是unbookmarkleted形式:
(function() {
var el=document.createElement('div'),
b=document.getElementsByTagName('body')[0];
otherlib=false,
msg='';
el.style.position='fixed';
el.style.height='32px';
el.style.width='220px';
el.style.marginLeft='-110px';
el.style.top='0';
el.style.left='50%';
el.style.padding='5px 10px 5px 10px';
el.style.zIndex = 1001;
el.style.fontSize='12px';
el.style.color='#222';
el.style.backgroundColor='#f99';
if(typeof jQuery!='undefined') {
msg='This page already using jQuery v'+jQuery.fn.jquery;
return showMsg();
} else if (typeof $=='function') {
otherlib=true;
}
// more or less stolen form jquery core and adapted by paul irish
function getScript(url,success){
var script=document.createElement('script');
script.src=url;
var head=document.getElementsByTagName("head")[0],
done=false;
// Attach handlers for all browsers
script.onload=script.onreadystatechange = function(){
if ( !done && (!this.readyState
this.readyState == "loaded" || this.readyState == "complete") ) {
done=true;
success();
}
};
head.appendChild(script);
}
getScript('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js',function() {
if (typeof jQuery=='undefined') {
msg='Sorry, but jQuery wasn\'t able to load';
} else {
msg='This page is now jQuerified with v' + jQuery.fn.jquery;
if (otherlib) {msg+=' and noConflict(). Use $jq(), not $().';}
}
return showMsg();
});
function showMsg() {
el.innerHTML=msg;
b.appendChild(el);
window.setTimeout(function() {
if (typeof jQuery=='undefined') {
b.removeChild(el);
} else {
jQuery(el).fadeOut('slow',function() {
jQuery(this).remove();
});
if (otherlib) {
$jq=jQuery.noConflict();
}
}
} ,2500);
}
})();