SlideShare a Scribd company logo
jQuery Internals
    + Cool Stuff
                  John Resig
http://ejohn.org/ - http://twitter.com/jeresig/
Overview
✦   Why we do what we do
✦   Features you may not know about
✦   New features coming
Parts of jQuery
✦   Common
✦   Selectors
✦   DOM Modification
✦   Events
✦   Sniffing
Chaining
✦   jQuery(quot;<li><a></a></li>quot;) // li
      .find(quot;aquot;) // a
        .attr(quot;hrefquot;, quot;http://ejohn.org/quot;) // a
        .html(quot;John Resigquot;) // a
      .end() // li
      .appendTo(quot;ulquot;);


✦   jQuery(quot;<li><a></a></li>quot;) // li
      .find(quot;aquot;) // a
        .attr(quot;hrefquot;, quot;http://ejohn.org/quot;) // a
        .html(quot;John Resigquot;) // a
        .andSelf() // li, a
          .addClass(“person”) // li, a
        .end() // a
      .end() // li
      .appendTo(quot;ulquot;);
Isolation
✦   jQuery shouldn’t affect outside code
    ✦ We’re good at this

✦   Outside code shouldn’t effect jQuery
    ✦ Getting better at this
    ✦ (Still hurt by Object.prototype)
jQuery Wrapper
✦   (function(){
      var jQuery = window.jQuery = function(){
        // ...
      };
    })();
✦   (function(){
      var foo = 5;

    })();
Plugin Wrapping
✦   (function($){
      // Your code...
    })(jQuery);
✦   (function(){
      var $ = jQuery;
      // Your code...
    })();
noConflict
✦   // Remove $
    var $jq = jQuery.noConflict();
✦   // Remove $ and jQuery
    jQuery.noConflict(true);
✦   Can even have multiple copies of jQuery
    on the page, simultaneously
noConflict
✦   (function(){
      var oldjQuery = window.jQuery;
      var jQuery = window.jQuery = function(){
        // ...
      };
      jQuery.noConflict = function(all){
        if ( all )
          window.jQuery = oldjQuery;
        return jQuery;
      };
    })();
Element Data
✦   Added in jQuery 1.2
✦   Attaching data to elements can be
    hazardous
✦   Store data:
    jQuery.data(elem, “name”, “value”);
✦   Read data:
    jQuery.data(elem, “name”);
✦   All data is stored in a central cache and
    completely garbage collected, as necessary
Element Data (cont.)
✦   Added in jQuery 1.2.3
✦   Can handle namespacing
    $(”div”).data(”test”, “original”);
    $(”div”).data(”test.plugin”, “new data”);
    $(”div”).data(”test”) == “original”; // true
    $(”div”).data(”test.plugin”) == “new data”; // true
✦   Advanced data handling can be overridden
    by plugins
    $(element).bind(”setData.draggable”, function(event, key, value){
        self.options[key] = value;
    }).bind(”getData.draggable”, function(event, key){
        return self.options[key];
    });
Selectors
How It Works
✦   How it currently works
✦   “div > p”
✦   Find all divs
    Loop through each div
    ✦ Find all child elements
      ✦ Verify if element is paragraph
How It Works
✦   “div p”
✦   Find all divs
    Loop through all divs
    ✦ Find all p, relative to the div

✦   Merge all results
✦   Figure out unique results
Sizzle
✦   http://github.com/jeresig/sizzle/tree/master
✦   New Selector Engine for jQuery
✦   1.5 - 4x faster than other libraries
✦   4KB Compressed
✦   No dependencies, can be used by other
    libraries (MochiKit, Prototype)
How Does it Work?
✦   Query Restructuring
✦   “div p”
✦   Find all p elements
    For each p element
    ✦ check if parent is div
      ✦ if not, traverse up farther
      ✦ if at top, remove element
      ✦ if so, save element

✦   No merging! No unique!
How Does it Work?
✦   Faster for some queries, slower for others
✦   Depends on the DOM structure
✦   “div > p” much faster, for example
✦   Built like how browsers query the DOM
Niceties
✦   Query Caching
✦   if ( document.addEventListener && !document.querySelectorAll ) {
      cache = {};
      function invalidate(){ cache = {}; }
      document.addEventListener(quot;DOMAttrModifiedquot;, invalidate, false);
      document.addEventListener(quot;DOMNodeInsertedquot;, invalidate, false);
      document.addEventListener(quot;DOMNodeRemovedquot;, invalidate, false);
    }


✦   Smart Fallbacks
✦   if ( document.getElementsByClassName ) {
      Expr.order.splice(1, 0, quot;CLASSquot;);
      Expr.find.CLASS = function(match, context) {
         return context.getElementsByClassName(match[1]);
      };
    }
Manipulation
✦   Four common methods:
    append, prepend, before, after
✦   $(“<li>and this too!</li>”)
✦   How does it work?
3-step Process
✦   Cleaning the input
✦   Converting it into a DOM
✦   Injecting it into the DOM
Cleaning
✦   Make sure we’re working with HTML
    input
✦   (Convert XML to HTML)
✦   <table/> -> <table></table>
✦   elem = elem.replace(/(<(w+)[^>]*?)/>/g, function(all, front,
    tag){
        return tag.match(/^(abbr|br|col|img|input|link|meta|param|
    hr|area|embed)$/i) ?
            all :
            front + quot;></quot; + tag + quot;>quot;;
    });
Converting
✦   Inject HTML string using innerHTML
✦   var div = document.createElement(“div”);
    div.innerHTML = html;
    div.childNodes; // Your meat!
✦   But doesn’t work for all HTML
✦   <tr>, <td>, <option>, <legend> (+ others)
    must be in correct container elements
✦   “<table><tbody>” + html + “</tbody></
    table>”
Injecting
✦   var elems = div.childNodes;
✦   Loop through elems, cloneNode(true)
    each, insert into DOM
    ✦ 5 paragraphs
    ✦ 100 divs
    ✦ 2 method calls (insert, clone)
    ✦ 1000 method

✦   *Very* slow
✦   Simple plugin provides 10-15x speed-up:
    http://dev.jquery.com/~john/ticket/append/
Document Fragments
✦   No div.childNodes looping
✦   Move the nodes into a Document
    Fragment
✦   Husk DOM container
✦   Whole container can be cloned
✦   and whole container can be injected
✦   Saves a ton of repetition
Events
Non-DOM Events
✦   function User(){}
✦   var user = new User();
✦   $(user).bind(“login”, function(){
      alert(“all done”);
    });

    $(user).trigger(“login”);
Namespaced Events
✦   Added in jQuery 1.2
✦   Targeted adding and removal of events
✦   $(“div”).bind(“click.foo”, function(){
      alert(“foo!”);
    });
✦   Time to clean up!
    $(“div”).unbind(“click.foo”);
✦   Added in jQuery 1.2.3:
    $(“div”).unbind(“.foo”);
Special Events
✦   Added in jQuery 1.2.2
✦   Can create whole shadow event system
✦   New events: mouseenter, mouseleave,
    mousewheel (w/ plugin), ready
✦   $(”li”).bind(”mouseenter”, function(){
      $(this).addClass(”hover”);
    }).bind(”mouseleave”, function(){
      $(this).removeClass(”hover”);
    });
Animations
✦   Full Animation plugin (in jQuery 1.2):
✦   jQuery.fx.step.corner = function(fx) {
      fx.elem.style.top = fx.now + fx.unit;
      fx.elem.style.left = fx.now + fx.unit;
    };
✦   $(”#go”).click(function(){
      $(”#block”).animate({corner: ‘40px’}, 500);
    });
Sniffing
✦   All major JS libraries use browser sniffing
✦   Look at the user agent and make guesses
✦   We can get rid of this!
✦   Makes our code more resilient to change
Testing & Analysis
Testing
✦   Rapid testing
✦   ./gen.sh
    #!/bin/sh
    svn co https://jqueryjs.googlecode.com/svn/trunk/jquery $1
      &> /dev/null
    cp $2.html $1/index.html
    cd $1
    make &> /dev/null


✦   ./gen.sh 1234 dom
Test Suite
✦   qUnit (jQuery Test Suite)
    http://docs.jquery.com/QUnit
✦   By Joern Zaefferer
qUnit Usage
✦   test(quot;a basic test examplequot;, function() {
      ok( true, quot;this test is finequot; );
      var value = quot;helloquot;;
      equals( quot;helloquot;, value, quot;We expect value to be helloquot; );
    });

    module(quot;Module Aquot;);
    test(quot;first test within modulequot;, function() {
      ok( true, quot;all passquot; );
    });
    test(quot;second test within modulequot;, function() {
      ok( true, quot;all passquot; );
    });

    module(quot;Module Bquot;);
    test(quot;some other testquot;, function() {
      expect(1);
      ok( true, quot;wellquot; );
    });
qUnit Output
Profiling
✦   Deep Profiling Plugin
✦   Watch all method calls and events
✦   http://ejohn.org/blog/deep-profiling-
    jquery-apps/
✦   http://dev.jquery.com/~john/plugins/profile/
    github.com.html
✦   javascript:jQuery.displayProfile();
Thank You!
✦   John Resig
✦   http://ejohn.org/
✦   http://twitter.com/jeresig/

More Related Content

What's hot

[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
FuncUnit
FuncUnitFuncUnit
FuncUnit
Brian Moschel
 
Reactive Type safe Webcomponents with skateJS
Reactive Type safe Webcomponents with skateJSReactive Type safe Webcomponents with skateJS
Reactive Type safe Webcomponents with skateJS
Martin Hochel
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Jeado Ko
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todaygerbille
 
The jQuery Library
The  jQuery LibraryThe  jQuery Library
The jQuery Library
LearnNowOnline
 
Reactive Type-safe WebComponents
Reactive Type-safe WebComponentsReactive Type-safe WebComponents
Reactive Type-safe WebComponents
Martin Hochel
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
TrevorBurnham
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 Apps
Doris Chen
 
jQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterprisejQuery in the [Aol.] Enterprise
jQuery in the [Aol.] Enterprise
Dave Artz
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
Tudor Barbu
 
Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007Netvibes
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for Programmers
David Rodenas
 
Bundling Client Side Assets
Bundling Client Side AssetsBundling Client Side Assets
Bundling Client Side AssetsTimothy Oxley
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
Tomi Juhola
 
Starting with jQuery
Starting with jQueryStarting with jQuery
Starting with jQuery
Anil Kumar
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
Remy Sharp
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
BlackCatWeb
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Eventsdmethvin
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh My
Steve McMahon
 

What's hot (20)

[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
FuncUnit
FuncUnitFuncUnit
FuncUnit
 
Reactive Type safe Webcomponents with skateJS
Reactive Type safe Webcomponents with skateJSReactive Type safe Webcomponents with skateJS
Reactive Type safe Webcomponents with skateJS
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
 
The jQuery Library
The  jQuery LibraryThe  jQuery Library
The jQuery Library
 
Reactive Type-safe WebComponents
Reactive Type-safe WebComponentsReactive Type-safe WebComponents
Reactive Type-safe WebComponents
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 Apps
 
jQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterprisejQuery in the [Aol.] Enterprise
jQuery in the [Aol.] Enterprise
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007
 
Basic Tutorial of React for Programmers
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for Programmers
 
Bundling Client Side Assets
Bundling Client Side AssetsBundling Client Side Assets
Bundling Client Side Assets
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Starting with jQuery
Starting with jQueryStarting with jQuery
Starting with jQuery
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh My
 

Viewers also liked

JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)jeresig
 
Processing and Processing.js
Processing and Processing.jsProcessing and Processing.js
Processing and Processing.js
jeresig
 
Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010
jeresig
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
 
Khan Academy Computer Science
Khan Academy Computer ScienceKhan Academy Computer Science
Khan Academy Computer Science
jeresig
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
jeresig
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 

Viewers also liked (7)

JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)
 
Processing and Processing.js
Processing and Processing.jsProcessing and Processing.js
Processing and Processing.js
 
Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010Testing Mobile JavaScript (Fall 2010
Testing Mobile JavaScript (Fall 2010
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Khan Academy Computer Science
Khan Academy Computer ScienceKhan Academy Computer Science
Khan Academy Computer Science
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 

Similar to jQuery Internals + Cool Stuff

DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQuery
Remy Sharp
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)
jeresig
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)
jeresig
 
jQuery 1.3 and jQuery UI
jQuery 1.3 and jQuery UIjQuery 1.3 and jQuery UI
jQuery 1.3 and jQuery UI
jeresig
 
YUI 3
YUI 3YUI 3
YUI 3
Dav Glass
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)
jeresig
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuerydeimos
 
Learning jQuery @ MIT
Learning jQuery @ MITLearning jQuery @ MIT
Learning jQuery @ MIT
jeresig
 
More Secrets of JavaScript Libraries
More Secrets of JavaScript LibrariesMore Secrets of JavaScript Libraries
More Secrets of JavaScript Libraries
jeresig
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)Carles Farré
 
DOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript FrameworkDOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript Framework
Matthew McCullough
 
Solr and symfony in Harmony with SolrJs
Solr and symfony in Harmony with SolrJsSolr and symfony in Harmony with SolrJs
Solr and symfony in Harmony with SolrJsWildan Maulana
 
the next web now
the next web nowthe next web now
the next web nowzulin Gu
 
Ditching JQuery
Ditching JQueryDitching JQuery
Ditching JQuery
howlowck
 
The Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J QueryThe Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J QueryQConLondon2008
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
goodfriday
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbai
Praveen Puglia
 
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery Plugins
Jörn Zaefferer
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 

Similar to jQuery Internals + Cool Stuff (20)

DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQuery
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)
 
jQuery 1.3 and jQuery UI
jQuery 1.3 and jQuery UIjQuery 1.3 and jQuery UI
jQuery 1.3 and jQuery UI
 
YUI 3
YUI 3YUI 3
YUI 3
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
 
Learning jQuery @ MIT
Learning jQuery @ MITLearning jQuery @ MIT
Learning jQuery @ MIT
 
More Secrets of JavaScript Libraries
More Secrets of JavaScript LibrariesMore Secrets of JavaScript Libraries
More Secrets of JavaScript Libraries
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
 
DOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript FrameworkDOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript Framework
 
Solr and symfony in Harmony with SolrJs
Solr and symfony in Harmony with SolrJsSolr and symfony in Harmony with SolrJs
Solr and symfony in Harmony with SolrJs
 
the next web now
the next web nowthe next web now
the next web now
 
Ditching JQuery
Ditching JQueryDitching JQuery
Ditching JQuery
 
The Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J QueryThe Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J Query
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbai
 
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery Plugins
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 

More from jeresig

Does Coding Every Day Matter?
Does Coding Every Day Matter?Does Coding Every Day Matter?
Does Coding Every Day Matter?
jeresig
 
Accidentally Becoming a Digital Librarian
Accidentally Becoming a Digital LibrarianAccidentally Becoming a Digital Librarian
Accidentally Becoming a Digital Librarian
jeresig
 
2014: John's Favorite Thing (Neo4j)
2014: John's Favorite Thing (Neo4j)2014: John's Favorite Thing (Neo4j)
2014: John's Favorite Thing (Neo4j)
jeresig
 
Computer Vision as Art Historical Investigation
Computer Vision as Art Historical InvestigationComputer Vision as Art Historical Investigation
Computer Vision as Art Historical Investigation
jeresig
 
Hacking Art History
Hacking Art HistoryHacking Art History
Hacking Art History
jeresig
 
Using JS to teach JS at Khan Academy
Using JS to teach JS at Khan AcademyUsing JS to teach JS at Khan Academy
Using JS to teach JS at Khan Academy
jeresig
 
Applying Computer Vision to Art History
Applying Computer Vision to Art HistoryApplying Computer Vision to Art History
Applying Computer Vision to Art History
jeresig
 
NYARC 2014: Frick/Zeri Results
NYARC 2014: Frick/Zeri ResultsNYARC 2014: Frick/Zeri Results
NYARC 2014: Frick/Zeri Results
jeresig
 
EmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image AnalysisEmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image Analysis
jeresig
 
Applying Computer Vision to Art History
Applying Computer Vision to Art HistoryApplying Computer Vision to Art History
Applying Computer Vision to Art History
jeresig
 
Introduction to jQuery (Ajax Exp 2006)
Introduction to jQuery (Ajax Exp 2006)Introduction to jQuery (Ajax Exp 2006)
Introduction to jQuery (Ajax Exp 2006)jeresig
 
jQuery Recommendations to the W3C (2011)
jQuery Recommendations to the W3C (2011)jQuery Recommendations to the W3C (2011)
jQuery Recommendations to the W3C (2011)jeresig
 
jQuery Open Source Process (RIT 2011)
jQuery Open Source Process (RIT 2011)jQuery Open Source Process (RIT 2011)
jQuery Open Source Process (RIT 2011)jeresig
 
jQuery Open Source Process (Knight Foundation 2011)
jQuery Open Source Process (Knight Foundation 2011)jQuery Open Source Process (Knight Foundation 2011)
jQuery Open Source Process (Knight Foundation 2011)jeresig
 
jQuery Mobile
jQuery MobilejQuery Mobile
jQuery Mobile
jeresig
 
jQuery Open Source (Fronteer 2011)
jQuery Open Source (Fronteer 2011)jQuery Open Source (Fronteer 2011)
jQuery Open Source (Fronteer 2011)
jeresig
 
Holistic JavaScript Performance
Holistic JavaScript PerformanceHolistic JavaScript Performance
Holistic JavaScript Performance
jeresig
 
New Features Coming in Browsers (RIT '09)
New Features Coming in Browsers (RIT '09)New Features Coming in Browsers (RIT '09)
New Features Coming in Browsers (RIT '09)
jeresig
 
Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)
jeresig
 
Advanced jQuery (Ajax Exp 2007)
Advanced jQuery (Ajax Exp 2007)Advanced jQuery (Ajax Exp 2007)
Advanced jQuery (Ajax Exp 2007)
jeresig
 

More from jeresig (20)

Does Coding Every Day Matter?
Does Coding Every Day Matter?Does Coding Every Day Matter?
Does Coding Every Day Matter?
 
Accidentally Becoming a Digital Librarian
Accidentally Becoming a Digital LibrarianAccidentally Becoming a Digital Librarian
Accidentally Becoming a Digital Librarian
 
2014: John's Favorite Thing (Neo4j)
2014: John's Favorite Thing (Neo4j)2014: John's Favorite Thing (Neo4j)
2014: John's Favorite Thing (Neo4j)
 
Computer Vision as Art Historical Investigation
Computer Vision as Art Historical InvestigationComputer Vision as Art Historical Investigation
Computer Vision as Art Historical Investigation
 
Hacking Art History
Hacking Art HistoryHacking Art History
Hacking Art History
 
Using JS to teach JS at Khan Academy
Using JS to teach JS at Khan AcademyUsing JS to teach JS at Khan Academy
Using JS to teach JS at Khan Academy
 
Applying Computer Vision to Art History
Applying Computer Vision to Art HistoryApplying Computer Vision to Art History
Applying Computer Vision to Art History
 
NYARC 2014: Frick/Zeri Results
NYARC 2014: Frick/Zeri ResultsNYARC 2014: Frick/Zeri Results
NYARC 2014: Frick/Zeri Results
 
EmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image AnalysisEmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image Analysis
 
Applying Computer Vision to Art History
Applying Computer Vision to Art HistoryApplying Computer Vision to Art History
Applying Computer Vision to Art History
 
Introduction to jQuery (Ajax Exp 2006)
Introduction to jQuery (Ajax Exp 2006)Introduction to jQuery (Ajax Exp 2006)
Introduction to jQuery (Ajax Exp 2006)
 
jQuery Recommendations to the W3C (2011)
jQuery Recommendations to the W3C (2011)jQuery Recommendations to the W3C (2011)
jQuery Recommendations to the W3C (2011)
 
jQuery Open Source Process (RIT 2011)
jQuery Open Source Process (RIT 2011)jQuery Open Source Process (RIT 2011)
jQuery Open Source Process (RIT 2011)
 
jQuery Open Source Process (Knight Foundation 2011)
jQuery Open Source Process (Knight Foundation 2011)jQuery Open Source Process (Knight Foundation 2011)
jQuery Open Source Process (Knight Foundation 2011)
 
jQuery Mobile
jQuery MobilejQuery Mobile
jQuery Mobile
 
jQuery Open Source (Fronteer 2011)
jQuery Open Source (Fronteer 2011)jQuery Open Source (Fronteer 2011)
jQuery Open Source (Fronteer 2011)
 
Holistic JavaScript Performance
Holistic JavaScript PerformanceHolistic JavaScript Performance
Holistic JavaScript Performance
 
New Features Coming in Browsers (RIT '09)
New Features Coming in Browsers (RIT '09)New Features Coming in Browsers (RIT '09)
New Features Coming in Browsers (RIT '09)
 
Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)
 
Advanced jQuery (Ajax Exp 2007)
Advanced jQuery (Ajax Exp 2007)Advanced jQuery (Ajax Exp 2007)
Advanced jQuery (Ajax Exp 2007)
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 

jQuery Internals + Cool Stuff

  • 1. jQuery Internals + Cool Stuff John Resig http://ejohn.org/ - http://twitter.com/jeresig/
  • 2. Overview ✦ Why we do what we do ✦ Features you may not know about ✦ New features coming
  • 3. Parts of jQuery ✦ Common ✦ Selectors ✦ DOM Modification ✦ Events ✦ Sniffing
  • 4. Chaining ✦ jQuery(quot;<li><a></a></li>quot;) // li .find(quot;aquot;) // a .attr(quot;hrefquot;, quot;http://ejohn.org/quot;) // a .html(quot;John Resigquot;) // a .end() // li .appendTo(quot;ulquot;); ✦ jQuery(quot;<li><a></a></li>quot;) // li .find(quot;aquot;) // a .attr(quot;hrefquot;, quot;http://ejohn.org/quot;) // a .html(quot;John Resigquot;) // a .andSelf() // li, a .addClass(“person”) // li, a .end() // a .end() // li .appendTo(quot;ulquot;);
  • 5. Isolation ✦ jQuery shouldn’t affect outside code ✦ We’re good at this ✦ Outside code shouldn’t effect jQuery ✦ Getting better at this ✦ (Still hurt by Object.prototype)
  • 6. jQuery Wrapper ✦ (function(){ var jQuery = window.jQuery = function(){ // ... }; })(); ✦ (function(){ var foo = 5; })();
  • 7. Plugin Wrapping ✦ (function($){ // Your code... })(jQuery); ✦ (function(){ var $ = jQuery; // Your code... })();
  • 8. noConflict ✦ // Remove $ var $jq = jQuery.noConflict(); ✦ // Remove $ and jQuery jQuery.noConflict(true); ✦ Can even have multiple copies of jQuery on the page, simultaneously
  • 9. noConflict ✦ (function(){ var oldjQuery = window.jQuery; var jQuery = window.jQuery = function(){ // ... }; jQuery.noConflict = function(all){ if ( all ) window.jQuery = oldjQuery; return jQuery; }; })();
  • 10. Element Data ✦ Added in jQuery 1.2 ✦ Attaching data to elements can be hazardous ✦ Store data: jQuery.data(elem, “name”, “value”); ✦ Read data: jQuery.data(elem, “name”); ✦ All data is stored in a central cache and completely garbage collected, as necessary
  • 11. Element Data (cont.) ✦ Added in jQuery 1.2.3 ✦ Can handle namespacing $(”div”).data(”test”, “original”); $(”div”).data(”test.plugin”, “new data”); $(”div”).data(”test”) == “original”; // true $(”div”).data(”test.plugin”) == “new data”; // true ✦ Advanced data handling can be overridden by plugins $(element).bind(”setData.draggable”, function(event, key, value){ self.options[key] = value; }).bind(”getData.draggable”, function(event, key){ return self.options[key]; });
  • 13. How It Works ✦ How it currently works ✦ “div > p” ✦ Find all divs Loop through each div ✦ Find all child elements ✦ Verify if element is paragraph
  • 14. How It Works ✦ “div p” ✦ Find all divs Loop through all divs ✦ Find all p, relative to the div ✦ Merge all results ✦ Figure out unique results
  • 15. Sizzle ✦ http://github.com/jeresig/sizzle/tree/master ✦ New Selector Engine for jQuery ✦ 1.5 - 4x faster than other libraries ✦ 4KB Compressed ✦ No dependencies, can be used by other libraries (MochiKit, Prototype)
  • 16. How Does it Work? ✦ Query Restructuring ✦ “div p” ✦ Find all p elements For each p element ✦ check if parent is div ✦ if not, traverse up farther ✦ if at top, remove element ✦ if so, save element ✦ No merging! No unique!
  • 17. How Does it Work? ✦ Faster for some queries, slower for others ✦ Depends on the DOM structure ✦ “div > p” much faster, for example ✦ Built like how browsers query the DOM
  • 18. Niceties ✦ Query Caching ✦ if ( document.addEventListener && !document.querySelectorAll ) { cache = {}; function invalidate(){ cache = {}; } document.addEventListener(quot;DOMAttrModifiedquot;, invalidate, false); document.addEventListener(quot;DOMNodeInsertedquot;, invalidate, false); document.addEventListener(quot;DOMNodeRemovedquot;, invalidate, false); } ✦ Smart Fallbacks ✦ if ( document.getElementsByClassName ) { Expr.order.splice(1, 0, quot;CLASSquot;); Expr.find.CLASS = function(match, context) { return context.getElementsByClassName(match[1]); }; }
  • 19. Manipulation ✦ Four common methods: append, prepend, before, after ✦ $(“<li>and this too!</li>”) ✦ How does it work?
  • 20. 3-step Process ✦ Cleaning the input ✦ Converting it into a DOM ✦ Injecting it into the DOM
  • 21. Cleaning ✦ Make sure we’re working with HTML input ✦ (Convert XML to HTML) ✦ <table/> -> <table></table> ✦ elem = elem.replace(/(<(w+)[^>]*?)/>/g, function(all, front, tag){ return tag.match(/^(abbr|br|col|img|input|link|meta|param| hr|area|embed)$/i) ? all : front + quot;></quot; + tag + quot;>quot;; });
  • 22. Converting ✦ Inject HTML string using innerHTML ✦ var div = document.createElement(“div”); div.innerHTML = html; div.childNodes; // Your meat! ✦ But doesn’t work for all HTML ✦ <tr>, <td>, <option>, <legend> (+ others) must be in correct container elements ✦ “<table><tbody>” + html + “</tbody></ table>”
  • 23. Injecting ✦ var elems = div.childNodes; ✦ Loop through elems, cloneNode(true) each, insert into DOM ✦ 5 paragraphs ✦ 100 divs ✦ 2 method calls (insert, clone) ✦ 1000 method ✦ *Very* slow ✦ Simple plugin provides 10-15x speed-up: http://dev.jquery.com/~john/ticket/append/
  • 24. Document Fragments ✦ No div.childNodes looping ✦ Move the nodes into a Document Fragment ✦ Husk DOM container ✦ Whole container can be cloned ✦ and whole container can be injected ✦ Saves a ton of repetition
  • 26. Non-DOM Events ✦ function User(){} ✦ var user = new User(); ✦ $(user).bind(“login”, function(){ alert(“all done”); }); $(user).trigger(“login”);
  • 27. Namespaced Events ✦ Added in jQuery 1.2 ✦ Targeted adding and removal of events ✦ $(“div”).bind(“click.foo”, function(){ alert(“foo!”); }); ✦ Time to clean up! $(“div”).unbind(“click.foo”); ✦ Added in jQuery 1.2.3: $(“div”).unbind(“.foo”);
  • 28. Special Events ✦ Added in jQuery 1.2.2 ✦ Can create whole shadow event system ✦ New events: mouseenter, mouseleave, mousewheel (w/ plugin), ready ✦ $(”li”).bind(”mouseenter”, function(){ $(this).addClass(”hover”); }).bind(”mouseleave”, function(){ $(this).removeClass(”hover”); });
  • 29. Animations ✦ Full Animation plugin (in jQuery 1.2): ✦ jQuery.fx.step.corner = function(fx) { fx.elem.style.top = fx.now + fx.unit; fx.elem.style.left = fx.now + fx.unit; }; ✦ $(”#go”).click(function(){ $(”#block”).animate({corner: ‘40px’}, 500); });
  • 30. Sniffing ✦ All major JS libraries use browser sniffing ✦ Look at the user agent and make guesses ✦ We can get rid of this! ✦ Makes our code more resilient to change
  • 32. Testing ✦ Rapid testing ✦ ./gen.sh #!/bin/sh svn co https://jqueryjs.googlecode.com/svn/trunk/jquery $1 &> /dev/null cp $2.html $1/index.html cd $1 make &> /dev/null ✦ ./gen.sh 1234 dom
  • 33. Test Suite ✦ qUnit (jQuery Test Suite) http://docs.jquery.com/QUnit ✦ By Joern Zaefferer
  • 34. qUnit Usage ✦ test(quot;a basic test examplequot;, function() { ok( true, quot;this test is finequot; ); var value = quot;helloquot;; equals( quot;helloquot;, value, quot;We expect value to be helloquot; ); }); module(quot;Module Aquot;); test(quot;first test within modulequot;, function() { ok( true, quot;all passquot; ); }); test(quot;second test within modulequot;, function() { ok( true, quot;all passquot; ); }); module(quot;Module Bquot;); test(quot;some other testquot;, function() { expect(1); ok( true, quot;wellquot; ); });
  • 36. Profiling ✦ Deep Profiling Plugin ✦ Watch all method calls and events ✦ http://ejohn.org/blog/deep-profiling- jquery-apps/ ✦ http://dev.jquery.com/~john/plugins/profile/ github.com.html ✦ javascript:jQuery.displayProfile();
  • 37. Thank You! ✦ John Resig ✦ http://ejohn.org/ ✦ http://twitter.com/jeresig/