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
91
jQuery最佳实践
jQuery使用心得
sokamal
September 23, 2013
Tweet
Share
More Decks by sokamal
See All by sokamal
RETINA时代的前端优化
ikamal
2
160
亚马逊的快速菜单
ikamal
1
110
Less_css_介绍.pdf
ikamal
1
64
Other Decks in Programming
See All in Programming
第3回関東Kaggler会_AtCoderはKaggleの役に立つ
chettub
3
890
密集、ドキュメントのコロケーション with AWS Lambda
satoshi256kbyte
0
170
CI改善もDatadogとともに
taumu
0
110
Pulsar2 を雰囲気で使ってみよう
anoken
0
230
Open source software: how to live long and go far
gaelvaroquaux
0
620
法律の脱レガシーに学ぶフロントエンド刷新
oguemon
5
730
Grafana Cloudとソラカメ
devoc
0
140
Amazon ECS とマイクロサービスから考えるシステム構成
hiyanger
2
490
Grafana Loki によるサーバログのコスト削減
mot_techtalk
1
110
技術を根付かせる / How to make technology take root
kubode
1
240
iOSエンジニアから始める visionOS アプリ開発
nao_randd
3
120
個人アプリを2年ぶりにアプデしたから褒めて / I just updated my personal app, praise me!
lovee
0
340
Featured
See All Featured
Making Projects Easy
brettharned
116
6k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
28
9.3k
Bash Introduction
62gerente
610
210k
A designer walks into a library…
pauljervisheath
205
24k
Agile that works and the tools we love
rasmusluckow
328
21k
It's Worth the Effort
3n
184
28k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
129
19k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
27
1.9k
GitHub's CSS Performance
jonrohan
1030
460k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
114
50k
Optimizing for Happiness
mojombo
376
70k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
29
4.6k
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