Contenu connexe Similaire à Inside jQuery (2011) (20) Inside jQuery (2011)1. Inside jQuery
Kenneth Auchenberg
Inside jQuery @auchenberg kenneth.io
2. Inside jQuery
Kenneth Auchenberg
Twitter Blog
Inside jQuery @auchenberg kenneth.io
3. About me
Bah
Inside jQuery @auchenberg kenneth.io
5. The basics.
jQuery.
Go Go Go!
Inside jQuery @auchenberg kenneth.io
9. Document
Location
History
Frames
BOM
Navigator Browser Object Model
Inside jQuery @auchenberg kenneth.io
10. HTML
DOM
Document Object Model
Inside jQuery @auchenberg kenneth.io
11. SVG DOM
Scalable Vector Graphics
MathML DOM
Mathematical Markup Langugage
SMIL DOM
Synchronized Multimedia Integration Language
DOM
Document Object Model
Inside jQuery @auchenberg kenneth.io
14. Closure Library
Frameworks
Abstractions
Inside jQuery @auchenberg kenneth.io
16. “ Looking at how Behaviour works, I've never
been completely happy - it simply seems too
tedious and verbose for everyday ”
John Resig
December 2005
Quote from http://ejohn.org/blog/selectors-in-javascript/
Inside jQuery @auchenberg kenneth.io
17. A: Behaviour B: pre-jQuery
Behaviour.register({ $('#example
li').bind('click',function(){
'#example
li':
function(e){
this.parentNode.removeChild(this);
e.onclick
=
function(){ });
this.parentNode.removeChild(this);
}
}
});
A:
Behaviour.register({'':function(e){e.on=}});
B:
$('').bind('',);
Syntax
Inside jQuery @auchenberg kenneth.io
18. A: Behaviour B: pre-jQuery
Behaviour.register({ $('#foo
ol
li')
'#foo
ol
li':
function(a)
{
.set('title','List
Items!')
a.title
=
"List
Items!";
.bind('click',function(){alert('Hello!');})
a.onclick
=
function(){alert('Hello!');};
.select('.tmp')
},
.style('color','white')
'#foo
ol
li.tmp':
function(a)
{
.select('.foo')
a.style.color
=
'white';
.style('background','red');
},
'#foo
ol
li.tmp
.foo':
function(a)
{
a.style.background
=
'red';
}
});
A:
Behaviour.register({'':function(a){a.=;a.on=;},'#foo
ol
li':function(a){a.style.='';},
B:
$('').set('','').bind('',).select('').style('','').select('').style('','');
Inside jQuery @auchenberg kenneth.io
19. jQuery
Prototype
Trend
October 2010
Scale is based on the average worldwide traffic of jquery javascript from 2004 to 2010.
Source: http://www.google.com/trends?q=dojo+javascript,+jquery+javascript,+yui+javascript,+prototype+javascript,+mootools+javascript&ctab=0&geo=all&date=all&sort=1
Inside jQuery @auchenberg kenneth.io
20. Prototype
jQuery Usage
October 2010
Distribution is calculated from a cross section of website domains provided by URLs entered at BuiltWith.com and the Quantcast Top Million. Last calculated on October 19 2010.
Source: http://trends.builtwith.com/javascript
Inside jQuery @auchenberg kenneth.io
22. var $ = ‘Hello World’;
var € = ‘Hello World’;
var @ = ‘Hello World’;
var _ = ‘Hello World’;
Identifies Names
Inside jQuery @auchenberg kenneth.io
23. “
7.6 Identifier Names and Identifiers
Identifier Names are tokens that are interpreted according
to the grammar given in the “Identifiers” section of chapter
5 of the Unicode standard, with some small modifications.
An Identifier is an IdentifierName that is not a
ReservedWord (see 7.6.1). The Unicode identifier
grammar is based on both normative and informative
character categories specified by the Unicode Standard.
The characters in the specified categories in version 3.0
of the Unicode standard must be treated as in those
categories by all conforming ECMAScript
implementations.
This standard specifies specific character additions: The
dollar sign ($) and the underscore (_) are permitted
anywhere in an IdentifierName. ECMA-262
…”
Quote from Standard ECMA-262 ECMAScript Language Specification
Inside jQuery @auchenberg kenneth.io
24. Utilities Traversing Attributes Effects
Core Selectors Manipulation CSS Events Ajax
jQuery
jQuery
Inside jQuery @auchenberg kenneth.io
25. Selectors & Performance
Events & Delegation
AJAX & Communication
Extensions & Community
Inside jQuery @auchenberg kenneth.io
27. 3.0+
9.0+
2.0+
6.0+
Browsers
1.0+
Inside jQuery @auchenberg kenneth.io
29. <!DOCTYPE
html>
<html>
<head>
<title>jQuery</title>
</head>
<body></body>
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/
jquery/1.4.3/jquery.min.js"></script>
</html>
Inject
Inside jQuery @auchenberg kenneth.io
31. jQuery code begins $
followed by a selector
and ends with action(s)
$(’div’).addClass(‘kenneth’);
$(’div.groups‐panel’).addClass(‘kenneth’).find(’span:first‐
child’).text(‘rocks’).show();
Inside jQuery @auchenberg kenneth.io
32. Selectors and actions can be attached to
events.
$(’body’).click(function()
{
$(’div’).addClass(‘kenneth’)
;
});
$(’body’).live(’click’,
function()
{
$(’div’).addClass(‘kenneth’)
;
});
Inside jQuery @auchenberg kenneth.io
34. document.getElementById('header')
document.getElementsByTagName('p')
document.getElementsByClassName(‘.hey’)
'body
>
div.wrapper
>
section'?
Browser selectors
Inside jQuery @auchenberg kenneth.io
35. document.getElementById('header')
document.getElementsByTagName('p')
document.getElementsByClassName(‘.hey’)
'body
>
div.wrapper
>
section'?
Browser selectors
Inside jQuery @auchenberg kenneth.io
38. !"#$ ;<"3-)$ ;+=(),"(->)?$ ;()5G+5"&#$
%&%'%()$ ;&,-)$ ;%'2)B$ ;<"3-)G+5"&#$
*+&,--$ ;(=)>-%&?$ ;5,->-%&?$ ;&,-)G+5"&#$
*+&,--*+&,--$ ;%6%($ ;2,3%()$ ;=(&BG+5"&#$
.$ ;=##$ ;5"##%($
-%&/0$-%&1$ ;%@>"(#%8?$ ;6"-":&%$ ;"(2H)$
;A)>"(#%8?$ ;<"&%$
2,3%()$4$+5"&#$ ;&)>"(#%8?$ .C,))3D$ ;:H))=($
23%6$7$(%8)$ ;5%,#%3$ .C,))3E6,&D$ ;%(,:&%#$
23%6$9$-":$ ;,("',)%#$ .C,))3FE6,&D$ ;+5%+I%#$
.C,))DC,))1D$ ;-%&%+)%#$
Selectors
Inside jQuery @auchenberg kenneth.io
39. • 2003.03.25: document.getElementsBySelector() by Simon Willison (later used in behaviour.js)[source]
• 2004.04.10: CssQuery() 1.0: by Dean Edwards
• 2005.08.19: CssQuery() 2.0.
• 2005.08.22: jSelect (precursor to jQuery)
• 2006.01.14: jQuery first release.
• 2006.01.18: Prototype. Initial release of selector engine.
• 2006.04.04: moo.dom (precursor to mootools
• 2006.08.26: jQuery 1.0
• 2006.11.14: Mochikit Selector. (orig. ported from prototype)
• 2007.01.08: jQuery 1.1a ("10-20x faster than 1.0")
• 2007.01.11: DomQuery by Jack Slocum (ExtJS).
• 2007.02.05: dojo.query().
• 2007.03.21: base2.DOM.
• 2007.05.01: Prototype 1.5.1
• 2007.05.07: Mootools 1.1
• 2007.07.01: jQuery 1.1.3 ("800% faster")
• 2007.07.10: Ext 1.1 RC1
•
•
2007.07.10: Dojo 0.9
2007.12.04: YUI 2.4.0
Timeline
• 2007.12.17: NWMatcher by Diego Perini
• 2008.08.25: Sizzle.js by John Resig
Source: http://paulirish.com/2008/javascript-css-selector-engine-timeline/
Inside jQuery @auchenberg kenneth.io
42. if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle, div = document.createElement("div");
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function(query, context, extra, seed){
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
if ( context.nodeType === 9 ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
querySelectorAll
Inside jQuery @auchenberg kenneth.io
44. $(ʻheader aʼ)
document.querySelectorAll(ʻheader aʼ)
????????
Selector break-down
Inside jQuery @auchenberg kenneth.io
46. Left to right Right to left
MooTools Sizzle
Ext.JS YUI 3
Prototype.js querySelectorAll
Direction
Inside jQuery @auchenberg kenneth.io
48. match:
{
ID:
/#((?:[wu00c0‐uFFFF‐]|.)+)/,
CLASS:
/.((?:[wu00c0‐uFFFF‐]|.)+)/,
NAME:
/[name=['"]*((?:[wu00c0‐uFFFF‐]|.)+)['"]*]/,
ATTR:
/[s*((?:[wu00c0‐uFFFF‐]|.)+)s*(?:(S?=)s*(['"]*)(.*?)3|)s*]/,
TAG:
/^((?:[wu00c0‐uFFFF*‐]|.)+)/,
CHILD:
/:(only|nth|last|first)‐child(?:((even|odd|[dn+‐]*)))?/,
POS:
/:(nth|eq|gt|lt|first|last|even|odd)(?:((d*)))?(?=[^‐]|$)/,
PSEUDO:
/:((?:[wu00c0‐uFFFF‐]|.)+)(?:((['"]?)((?:([^)]+)|[^()]*)+)2))?/
},
.find(ʻaʼ)
Inside jQuery @auchenberg kenneth.io
51.
CLASS:
function(match,
curLoop,
inplace,
result,
not,
isXML){
match
=
"
"
+
match[1].replace(//g,
"")
+
"
";
if
(
isXML
)
{
return
match;
}
for
(
var
i
=
0,
elem;
(elem
=
curLoop[i])
!=
null;
i++
)
{
if
(
elem
)
{
if
(
not
^
(elem.className
&&
("
"
+
elem.className
+
"
").replace(/[tn]/g,
"
").indexOf(match)
>=
0)
)
{
if
(
!inplace
)
{
result.push(
elem
);
}
}
else
if
(
inplace
)
{
curLoop[i]
=
false;
}
}
}
},
return
false;
.find(ʻ.headerʼ)
Inside jQuery @auchenberg kenneth.io
52. $(ʻdiv.me .projectsʼ)
$(ʻ.me div.projectsʼ)
http://jsperf.com/sizzle-selector-performance
Inside jQuery @auchenberg kenneth.io
54. cache vs. no-cache
http://jsperf.com/cache-jquery-objects
Inside jQuery @auchenberg kenneth.io
55. jQuery.each vs. for loop
http://jsperf.com/jquery-each-vs-for-loop/11
Inside jQuery @auchenberg kenneth.io
58. jQuery vs. HtmlEncode
http://jsperf.com/jquery-htmlencode-vs-string-replace/3
Inside jQuery @auchenberg kenneth.io
59. (build) string vs. object
http://jsperf.com/build-appended-object-test/3
Inside jQuery @auchenberg kenneth.io
61. .bind(eventname,
function)
.click,
.hover,
.mouseover
.unbind(eventname)
.focus,
.submit
.trigger(eventname,
function)
.live(eventname,
function)
.delegate(eventname,
function)
$(’body’).click(function() {
$(’div’).addClass(’zyb’) ;
});
Events
Inside jQuery @auchenberg kenneth.io
62. $(’body’).click(function()
{
$(’div’).addClass(‘kenneth’)
;
});
$(’body’).live(‘click’,
function()
{
$(’div’).addClass(‘kenneth’)
;
});
$(’body’).delegate(‘div’,
‘click’,
function()
{
$(’div’).addClass(‘kenneth’)
;
}); Event delegation
Inside jQuery @auchenberg kenneth.io
64. <ul class="myList">
<li class="red">The first item.</li>
<li class="green">The second item.</li>
<li class="yellow">The third item.</li>
<li class="blue">The fourth item.</li>
</ul>
<p>Class of the last clicked item: <span id="display"> </span></p>
$(’ul’).click(function(event) {
if(event.target.nodeName == ”LI”) {
$(’#display’).text(event.target.className);
}
});
How does it work?
Inside jQuery @auchenberg kenneth.io
65. <ul class="myList">
<li class="red"><b>The <i>first <u>item</u></i></b>.</li>
<li class="green"><b>The <i>second <u>item</u></i></b>.</li>
<li class="yellow"><b>The <i>third <u>item</u></i></b>.</li>
<li class="blue"><b>The <i>fourth <u>item</u></i></b>.</li>
</ul>
<p>Class of the last clicked item: <span id="display"> </span></p>
$("ul").click( function( event ) {
var elem = event.target;
while( elem.nodeName != "LI" && elem.parentNode) {
elem = elem.parentNode;
}
if(elem.nodeName == "LI") {
$("#display").text(event.target.className);
}
What if inside?
});
Inside jQuery @auchenberg kenneth.io
66. <ul
class="myList">
<li
class="red"><b>The
<i>first
<u>item</u></i></b>.</li>
<li
class="green"><b>The
<i>second
<u>item</u></i></b>.</li>
<li
class="yellow"><b>The
<i>third
<u>item</u></i></b>.</li>
<li
class="blue"><b>The
<i>fourth
<u>item</u></i></b>.</li>
</ul>
<p>Class
of
the
last
clicked
item:
<span
id="display">
</span></p>
$("ul").click(
function(
event
)
{
var
$elem
=
$(event.target).closest("li");
if($elem.length)
{
$("#display").text($elem.attr("class"));
}
});
Closest to the
rescue
Inside jQuery @auchenberg kenneth.io
67. <ul
class="myList">
<li
class="red"><b>The
<i>first
<u>item</u></i></b>.</li>
<li
class="green"><b>The
<i>second
<u>item</u></i></b>.</li>
<li
class="yellow"><b>The
<i>third
<u>item</u></i></b>.</li>
<li
class="blue"><b>The
<i>fourth
<u>item</u></i></b>.</li>
</ul>
<p>Class
of
the
last
clicked
item:
<span
id="display">
</span></p>
$("ul.myList
>
li").live("click",
function(e)
{
$("#display").text(
$(this).attr("class")
);
});
$("ul").delegate("li",
"click",
function(e)
{
$("#display").text(
.live & .delegate
$(this).attr("class")
);
});
Inside jQuery @auchenberg kenneth.io
68. EventHelper
=
(function
(window,
$,
undefined)
{
function
proxy_callback(callback,
shouldPreserveDefault,
e)
{
var
target
=
$(e.currentTarget);
if
(!shouldPreserveDefault)
{
e.preventDefault();
}
callback.apply(this,
[target].concat(Array.prototype.slice.call(arguments).slice(2)));
}
function
bind(eventType,
selector,
fn,
shouldPreserveDefault)
{
$('body').delegate(selector,
eventType,
proxy_callback.curry(fn,
shouldPreserveDefault));
}
function
unbind(eventType,
selector)
{
$('body').undelegate(selector,
eventType);
} Wrappers
})(window,
jQuery);
Inside jQuery @auchenberg kenneth.io
70. .ajax(options)
.get(url,
data,
callback,
dateType)
.post(url,
data,
callback,
dateType)
.getJSON(url,
data,
callback,
dateType)
.getScript(url,
callback)
.load(url,
data,
callback)
.ajaxComplete()
.ajaxSetup(options)
.ajaxStart()
.ajaxStop()
.ajaxSuccess()
.ajaxError()
Ajax in jQuery
Inside jQuery @auchenberg kenneth.io
71. .ajax(options)
.get(url,
data,
callback,
dateType)
.post(url,
data,
callback,
dateType)
.getJSON(url,
data,
callback,
dateType)
.getScript(url,
callback)
.load(url,
data,
callback)
.ajaxComplete()
.ajaxSetup(options)
.ajaxStart()
.ajaxStop()
.ajaxSuccess()
.ajaxError()
Ajax in jQuery
Inside jQuery @auchenberg kenneth.io
72. .ajax(options)
.get(url,
data,
callback,
dateType)
.post(url,
data,
callback,
dateType)
.getJSON(url,
data,
callback,
dateType)
.getScript(url,
callback)
.load(url,
data,
callback)
.ajaxComplete()
.ajaxSetup(options)
.ajaxStart()
.ajaxStop()
.ajaxSuccess()
.ajaxError()
Ajax in jQuery
Inside jQuery @auchenberg kenneth.io
74. CORS
Cross-Origin Resource Sharing
Inside jQuery @auchenberg kenneth.io
76. CORS
Cross-Origin Resource Sharing
Inside jQuery @auchenberg kenneth.io
80. $.get(“http://bar.other/resources/public‐data”,
function()
{
console.log(arguments);
},
“xml”)
GET /resources/public-data/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/
3.1b3pre
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://foo.example/examples/access-control/simpleXSInvocation.html
Origin: http://foo.example
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 00:23:53 GMT
Server: Apache/2.0.61
Access-Control-Allow-Origin: *
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/xml
[XML Data]
Inside jQuery @auchenberg kenneth.io
82. TwitterAPI = function() {
function getUserData(username) {
$.getJSON('http://twitter.com/status/user_timeline/' + username + '.json?count=10&callback=?', onSucesss);
}
function onSuccess(responseData) {
// to render
}
return {
getUserData: getUserData
}
}();
TwitterAPI.getUserData('auchenberg');
JSONP
JSON with Padding
Inside jQuery @auchenberg kenneth.io
85. Chat server
(socket.io)
XHR Long-polling XHR Multipart WebSockets
IE Firefox Chrome
Real time
Inside jQuery @auchenberg kenneth.io
87. MIME‐Version:
1.0 HTTP/1.1
200
OK
Content‐Type:
multipart/mixed;
boundary="frontier" Content‐Type:
text/plain
Transfer‐Encoding:
chunked
This
is
a
message
with
multiple
parts
in
MIME
format.
‐‐frontier 25
Content‐Type:
text/plain This
is
the
data
in
the
first
chunk
This
is
the
body
of
the
message. 1C
‐‐frontier and
this
is
the
second
one
Content‐Type:
application/octet‐stream
Content‐Transfer‐Encoding:
base64 0
PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZ
XHR Multipart
MIME
Inside jQuery @auchenberg kenneth.io
91. (function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
jquery.mouseWheel
return this.unbind("mousewheel", fn);
} Custom events
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
Inside jQuery
if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
@auchenberg kenneth.io
if ( event.detail ) { delta = -event.detail/3; }
92. });
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
if ( event.detail ) { delta = -event.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return $.event.handle.apply(this, args);
}
})(jQuery);
jquery.mouseWheel
Custom events
http://github.com/brandonaaron/jquery-mousewheel
Inside jQuery @auchenberg kenneth.io
93. var person = {};
$("form").link(person);
$("#name").val("foo");
alert(person.name); // foo
// ... user changes value ...
alert(person.name); // <user typed value>
$(person).data("name", "bar");
alert($("#name").val()); // bar
jquery.dataLink
Databinding
http://github.com/jquery/jquery-datalink
Inside jQuery @auchenberg kenneth.io
95. Be the cool kid
Inside jQuery @auchenberg kenneth.io
Notes de l'éditeur \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n Firefox - ES5 / native\n \n Firefox - ES5 / native\n Firefox - ES5 / native\n Firefox - ES5 / native\n Firefox - ES5 / native\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n