SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
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/

Mais conteúdo relacionado

Mais procurados

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 today
gerbille
 
Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007
Netvibes
 
Bundling Client Side Assets
Bundling Client Side AssetsBundling Client Side Assets
Bundling Client Side Assets
Timothy Oxley
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
dmethvin
 

Mais procurados (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
 

Destaque (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
 

Semelhante a jQuery Internals + Cool Stuff

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
deimos
 
[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é
 
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
Wildan Maulana
 
the next web now
the next web nowthe next web now
the next web now
zulin Gu
 
The Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J QueryThe Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J Query
QConLondon2008
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 

Semelhante a 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
 

Mais de 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
 

Mais de 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)
 

Último

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

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/