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
Modern Angular with Signals and Signal Store:New Rules for Your Architecture @enterJS Advanced Angular Day 2025
manfredsteyer
PRO
0
200
すべてのコンテキストを、 ユーザー価値に変える
applism118
3
1.2k
初学者でも今すぐできる、Claude Codeの生産性を10倍上げるTips
s4yuba
16
10k
今ならAmazon ECSのサービス間通信をどう選ぶか / Selection of ECS Interservice Communication 2025
tkikuc
21
3.9k
iOS 26にアップデートすると実機でのHot Reloadができない?
umigishiaoi
0
120
Discover Metal 4
rei315
2
120
A2A プロトコルを試してみる
azukiazusa1
2
1.3k
PHPで始める振る舞い駆動開発(Behaviour-Driven Development)
ohmori_yusuke
2
330
Composerが「依存解決」のためにどんな工夫をしているか #phpcon
o0h
PRO
1
250
技術同人誌をMCP Serverにしてみた
74th
1
630
LT 2025-06-30: プロダクトエンジニアの役割
yamamotok
0
710
CursorはMCPを使った方が良いぞ
taigakono
1
240
Featured
See All Featured
Building an army of robots
kneath
306
45k
Six Lessons from altMBA
skipperchong
28
3.9k
The Cult of Friendly URLs
andyhume
79
6.5k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
181
53k
We Have a Design System, Now What?
morganepeng
53
7.7k
Building Flexible Design Systems
yeseniaperezcruz
328
39k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
10
950
Side Projects
sachag
455
42k
Documentation Writing (for coders)
carmenintech
72
4.9k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
29
9.5k
The World Runs on Bad Software
bkeepers
PRO
69
11k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
8
810
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