Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
jQuery最佳实践
Search
sokamal
September 23, 2013
Programming
1
93
jQuery最佳实践
jQuery使用心得
sokamal
September 23, 2013
Tweet
Share
More Decks by sokamal
See All by sokamal
RETINA时代的前端优化
ikamal
2
180
亚马逊的快速菜单
ikamal
1
110
Less_css_介绍.pdf
ikamal
1
67
Other Decks in Programming
See All in Programming
データの民主化を支える、透明性のあるデータ利活用への挑戦 2025-06-25 Database Engineering Meetup#7
y_ken
0
340
Select API from Kotlin Coroutine
jmatsu
1
220
ニーリーにおけるプロダクトエンジニア
nealle
0
730
Result型で“失敗”を型にするPHPコードの書き方
kajitack
5
570
ソフトウェア品質を数字で捉える技術。事業成長を支えるシステム品質の マネジメント
takuya542
0
1.8k
XP, Testing and ninja testing
m_seki
3
220
PostgreSQLのRow Level SecurityをPHPのORMで扱う Eloquent vs Doctrine #phpcon #track2
77web
2
480
ふつうの技術スタックでアート作品を作ってみる
akira888
0
320
C++20 射影変換
faithandbrave
0
560
git worktree × Claude Code × MCP ~生成AI時代の並列開発フロー~
hisuzuya
1
520
AIプログラマーDevinは PHPerの夢を見るか?
shinyasaita
1
190
High-Level Programming Languages in AI Era -Human Thought and Mind-
hayat01sh1da
PRO
0
710
Featured
See All Featured
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
16k
Optimising Largest Contentful Paint
csswizardry
37
3.3k
How STYLIGHT went responsive
nonsquared
100
5.6k
Six Lessons from altMBA
skipperchong
28
3.9k
Designing for Performance
lara
609
69k
Facilitating Awesome Meetings
lara
54
6.4k
Building Applications with DynamoDB
mza
95
6.5k
Designing Experiences People Love
moore
142
24k
YesSQL, Process and Tooling at Scale
rocio
173
14k
How GitHub (no longer) Works
holman
314
140k
Gamification - CAS2011
davidbonilla
81
5.3k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
Transcript
jQuery最佳实践若干 Several jQuery Best Practices ECD Kamalyu
1 jQuery 几种不同的写法区别 window.jQuery = window.$ = jQuery; 没有区别
2 8000墙了jQuery CDN? <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jqu ery.min.js"></script> http://static.paipaiimg.com/qqbuy/js/lib/jquery-1.8.3.min.js <script>!window.jQuery && document.write(
'<script src="js/jquery-1.8.3.min.js">\x3C/script> ')</script>
3 jQuery 函数入口 $(document).ready(function() {...}) 可以改成 $(function() {...}) 源码 //
HANDLE: $(function) // Shortcut for document ready if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); }
3 jQuery 函数入口 $()这个函数可以当成入口 其他函数都移到外面 ajax方法也类似 success()中的匿名方法不方便调试和修改
4 避免创建多个jQuery对象 同一个函数里面 jQuery 对象应该缓存 $('#elem').hide(); $('#elem').html('bla'); $('#elem').otherStuff(); var _elem
= $('#elem'); 同样,$(this) 也应该缓存 var _this = $(this);
4 避免创建多个jQuery对象 尽量用链式写法,或者用本地变量 cur.removeClass("active"); cur.next().addClass("active"); 可以改写成 cur.removeClass("active").next().addClass("active");
5 用代理事件避免重复绑定 // bad $('li').each(function(){ $('this').find('.item').click(function() { ... }); })
// better $('#container').delegate(".item", "click", function() { ... }); $('#container').on("click", ".item", function() { ... }); 绑定事件的一些区别 http://www.haipi8.com/javascript/232
6 动画方法链式执行 需要放到回调函数中 $("p").click(function(e){ $(this).fadeOut("slow", function(){ $(this).remove(); }); });
7 创建对象的时候传入属性 $('</a>', { id : 'someId', className : 'someClass',
href : 'somePath.html' });
8 修改样式 `$(this).css` 虽然高效 但是不利于修改 应该只修改class,样式定义在CSS中
9 选择器优化 只要选择器写的不是太复杂 jQuery会自动优化执行 一般不用担心性能
9 选择器优化 但是有一点是真的可以优化的 // Fine in modern browsers, though Sizzle
does begin "running" $('#someDiv p.someClass').hide(); // Better for all browsers, and Sizzle never inits. $('#someDiv').find('p.someClass').hide();
9 选择器优化 现代浏览器支持QuerySelectorAll var matches = document.querySelectorAll("div.note, div.alert"); jQuery会直接调用浏览器内置函数 不会激活Sizzle
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
9 选择器优化 IE6/IE7 会激活Sizzle引擎 //Sizzle 工作方式 将选择器分成数组 ['#someDiv, 'p']; 然后从右到左匹配
而改成find以后 $('#someDiv').find('p') 两个单独的查询都可以调用浏览器内置方法查询 getElementbyId, getElementsByTagName
9 选择器优化 加上Context $('.someElements', '#someContainer').hide(); $('#someContainer').find('.someElements').hide(); // HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr) } else { return jQuery( context ).find( selector ); }
10 避免冲突 var j = jQuery.noConflict(); // 现在我们就可以用j代替$了 j('#someDiv').hide(); //
下面的代码中$代表的别的函数 $('someDiv').style.display = 'none';
10 避免冲突 创建作用域 (function($) { // 此处$会指向 jQuery 的 $
})(jQuery);
11 清空元素内容 obj.html(""); 可以改成 obj.empty(); empty做了事件解除绑定的操作,防止内存泄漏
11 清空元素内容 for ( ; (elem = this[i]) != null;
i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } }
12 尽量避免JS中拼字符串 可以把Template代码写到html文件或者单独的文件中 <script id="tpl_list" type="text/template"> <li class="book"> <img alt="bookcover"
src="bookcover/{coverImg}" /> <div class="bookName">{bookName}</div> <div class="authors">{authors}</div> </li> </script> 坑:正常的浏览器 var tpl = $('#tpl_list').html(); 或 var tpl = $('#tpl_list').text(); IE必须用 var tpl = $('#tpl_list').innerHTML;
13 toggle() 没有了 .toggle( handler(eventObject), handler(eventObject) [, handler(eventObject) ] )
toggle [ˈtɑɡəl] 切换 1.0 加入,1.9 移除
14 减少操作dom的次数 someDivs.each(function() { $('#anotherDiv')[0].innerHTML += $(this).text(); }); var someDivs
= $('#container').find('.someDivs'), contents = []; someDivs.each(function() { contents.push( this.innerHTML ); }); $('#anotherDiv').html( contents.join('') );
14 减少操作dom的次数 var someUls = $('#container').find('.someUls'), frag = document.createDocumentFragment(), li;
someUls.each(function() { li = document.createElement('li'); li.appendChild( document.createTextNode(this.innerHTML) ); frag.appendChild(li); }); $('#anotherUl')[0].appendChild( frag );
参考链接 绑定事件的一些区别 http://www.haipi8.com/javascript/232 jquery 手册 http://www.css88.com/jqapi-1.9/on/ 如何做到 jQuery-free? http://www.ruanyifeng.com/blog/2013/05/jquery-free.html jQuery
best practices http://net.tutsplus.com/tutorials/javascript-ajax/14-helpful-jquery-tricks-notes-and-best- practices/ Drupal jQuery best practices https://drupal.org/node/1720586
jQuery最佳实践若干 Several jQuery Best Practices ECD Kamalyu Thank you