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
94
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
実用的なGOCACHEPROG実装をするために / golang.tokyo #40
mazrean
1
270
Namespace and Its Future
tagomoris
6
700
意外と簡単!?フロントエンドでパスキー認証を実現する WebAuthn
teamlab
PRO
2
750
Reading Rails 1.0 Source Code
okuramasafumi
0
190
ProxyによるWindow間RPC機構の構築
syumai
3
1.2k
Android端末で実現するオンデバイスLLM 2025
masayukisuda
1
150
知っているようで知らない"rails new"の世界 / The World of "rails new" You Think You Know but Don't
luccafort
PRO
1
140
go test -json そして testing.T.Attr / Kyoto.go #63
utgwkk
3
300
Improving my own Ruby thereafter
sisshiki1969
1
160
請來的 AI Agent 同事們在寫程式時,怎麼用 pytest 去除各種幻想與盲點
keitheis
0
120
テストカバレッジ100%を10年続けて得られた学びと品質
mottyzzz
2
590
CloudflareのChat Agent Starter Kitで簡単!AIチャットボット構築
syumai
2
490
Featured
See All Featured
The Pragmatic Product Professional
lauravandoore
36
6.9k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3k
Designing Experiences People Love
moore
142
24k
Fireside Chat
paigeccino
39
3.6k
Writing Fast Ruby
sferik
628
62k
How GitHub (no longer) Works
holman
315
140k
Fantastic passwords and where to find them - at NoRuKo
philnash
52
3.4k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
131
19k
Visualization
eitanlees
148
16k
Building Better People: How to give real-time feedback that sticks.
wjessup
368
19k
Typedesign – Prime Four
hannesfritz
42
2.8k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
44
2.5k
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