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
エンジニア向け採用ピッチ資料
inusan
0
180
WebViewの現在地 - SwiftUI時代のWebKit - / The Current State Of WebView
marcy731
0
110
Blazing Fast UI Development with Compose Hot Reload (droidcon New York 2025)
zsmb
1
280
LINEヤフー データグループ紹介
lycorp_recruit_jp
0
1.9k
Code as Context 〜 1にコードで 2にリンタ 34がなくて 5にルール? 〜
yodakeisuke
0
120
What Spring Developers Should Know About Jakarta EE
ivargrimstad
0
400
RailsGirls IZUMO スポンサーLT
16bitidol
0
160
来たるべき 8.0 に備えて React 19 新機能と React Router 固有機能の取捨選択とすり合わせを考える
oukayuka
2
890
C++20 射影変換
faithandbrave
0
560
git worktree × Claude Code × MCP ~生成AI時代の並列開発フロー~
hisuzuya
1
530
#QiitaBash MCPのセキュリティ
ryosukedtomita
0
900
Node-RED を(HTTP で)つなげる MCP サーバーを作ってみた
highu
0
120
Featured
See All Featured
A designer walks into a library…
pauljervisheath
207
24k
No one is an island. Learnings from fostering a developers community.
thoeni
21
3.4k
Visualization
eitanlees
146
16k
Why Our Code Smells
bkeepers
PRO
337
57k
Imperfection Machines: The Place of Print at Facebook
scottboms
267
13k
Git: the NoSQL Database
bkeepers
PRO
430
65k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
657
60k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
29
1.8k
Fashionably flexible responsive web design (full day workshop)
malarkey
407
66k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
252
21k
Docker and Python
trallard
44
3.5k
Automating Front-end Workflow
addyosmani
1370
200k
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