我从jQuery源码中学到的10堂课

2011-04-22 09:54

我从jQuery源码中学到的10堂课

by yuanyi

at 2011-04-22 01:54:47

original http://heikezhi.com/2011/04/21/10-things-i-learned-from-the-jquery-source/

这是Paul Irish录制的一段讲述他从jQuery源码中学到的10堂课的非常生动有趣的视频,因为是在TXJS会议现场录制的,所以有点拖沓,如果翻墙不便或者没有时间,可以看看下面我总结的亮点,每一条都很受用:

1. jQuery的精华所在:

(function(window,document,undefined){ ... })(this,this.document);

2. jQuery.props

$(elem).attr('averylongattribute', 'some value');
$.props['avla'] = 'averylongattribute';
$('elem').attr('avla', 'aaaa');

3. jQuery.noConflict, 防止命名冲突的绝佳实现

4. 自定义fade speed

jQuery.fx.speeds.fastopen = ($.browser.msie & $.browser.version < 8) ? 800 : 400;
$("#stuff").fadeIn("fastopen");

5. $.getJSON()以及$.getScript(),下面是一段很神奇的代码,一定要在firebug或者inspector中执行一下:

$.getScript('http://www.cornify.com/js/cornify.js',  function(){
  var times = [42, 28, 75, 50, 62];
        times = times[Math.floor(Math.random()*times.length)];

  while(--times)
    cornify_add();
});

6. selector performance, $("#id").find("tag.thing") 快于 $("#id tag.thing")

7. JSON parse, 优先使用原生JSON parser

window.JSON && window.JSON.parse ?
                  window.JSON.parse(data) :
                  (new Function("return " + data))();

8. $.unique, 扩展unique方法可以作用于所有元素:http://paulirish.com/2010/duck-punching-with-jquery/

$.unique(["first", 7, true, 2, 7, true, 'last', 'last']); // ['first', 7. true, 2, 'last']

9. delay,如果想直接使用delay,可以试试下面的方法:

$(elem).fadeIn().delay(2000).fadeOut();
$(elem).queue(function() {
     $(elem).delay(2000).fadeOut();
});

10. jQuery.support和Makefile

如果还没尽兴,这里还有一个升级版的11堂课:http://www.youtube.com/watch?v=ARnp9Y8xgR4&feature=related

想和我们一道传播黑客精神?快来加入吧!

Creative Commons Attribution 3.0 Unported 此作品采用 Creative Commons Attribution 3.0 Unported.

无觅猜您也喜欢:

jQuery事件处理: 别再乱用“return false”了

世界,你准备好了吗?

打印从1到1000的整数,无循环,不判断

蛋疼之字母人像
无觅