SlideShare a Scribd company logo
1 of 39
Download to read offline
Advancing JavaScript
  with Libraries
                John Resig
  ejohn.org / jquery.com / mozilla.com
Two Hats
•   Mozilla Corp               •   jQuery JavaScript
                                   Library
•   FUEL
                               •   Released Jan 2006
    •   JS Lib for Ext. Devs
                               •   Small Filesize
    •   Reduce Complexity
                               •   Short, concise, code
•   JS Lib Test Suites
                               •   Extensible via plugins
    •   Integration, better
        coverage
Libraries are...


• ...abstractions away from existing APIs
• ...giving us new APIs to interface with
Hypothesis

• APIs breed patterns
• Libraries build new patterns on top of
  existing APIs
• New library patterns advance development
  in meaningful, considerable, ways
Why Create A Library?

• Distance ourselves from repetition
• In JavaScript:
 • Distance from browser differences
• In C (stdlib):
 • Distance from platform differences
DOM API

• Implemented in every modern browser
• Most stable of all the JavaScript APIs
• Very well documented
Fails in IE 7
JavaScript:
document.getElementById(“obj”)
  .getElementsByTagName(“*”)




HTML:
<object id=”obj”>
  <param name="src" value="test.mov"/>
  <param name="title" value="My Video"/>
</object>
Fails in Safari 2
JavaScript:
document.getElementById(“opt”).selected




HTML:
<div style=”display: none;”>
  <select><option id=”opt” value=”test”/></select>
</div>
Genuine Bugs
Fails in Opera & IE
JavaScript:
document.getElementById(“q”)




HTML:
<form action="" method="POST">
  <input type="text" name="q"/>
  <span id="q">Search</span>
</form>
Fails in Opera & IE
JavaScript:
var f = document.getElementsByTagName(“input”);
for ( var i = 0; i < f.length; i++ ) { ... }




HTML:
<form action="" method="POST">
  Num Rows: <input type="text" id="length" value="22"/><br/>
  <input type="submit" value="Generate"/>
</form>
Re-interpretation
   of the Spec
Fails in All
JavaScript:
document.getElementById(“name”)
  .setAttribute(“disabled”, false);




HTML:
<input type=”text” id=”name” disabled=”disabled”/>
Fails in All
JavaScript:
document.body.setAttribute(“class”, “home”);




HTML:
<body> ... </body>
What you expect
Why are Libraries
       Created?
• Browsers have a large number of strange
  differences...
  • IE has a lot of well documented bugs
  • Safari has less, but more obscure, bugs
• APIs don’t do what you expect
• When the API is impossible to learn, but
  through experience
Break down into
      Meta-Problems

• Waiting for the document to load
• Traversing the DOM
• Injecting HTML into a page
Waiting for the DOM
       to load

• A DOM document must be fully loaded
  before you can work with it
• Waiting for the window to load causes
  flashes of un-effected content
Focusing an input
<input type=”text” id=”test”/>
<script>document.getElementById(“test”).focus();</script>




<head><script src=”script.js”</head>

$(document).ready(function(){
  $(“#test”).focus();
});
Traversing the DOM

• getElementsByTagName, getElementById,
  getAttribute, nextSibling, previousSibling,
  parentNode, className, etc.
• A lot to learn and get right
• Has the potential to be very tricky (and
  long-winded)
DOM Selectors

• Goal: Improve the DOM Traversal API
• Provide an API on top of the existing DOM
  API
• Look to standards for inspiration
Types of Selectors
• XPath Selectors
 • //div/span[2]
 • /html[@id=’home’]
• CSS 3 Selectors
 • div > span:nth-of-type(2)
 • html:root#home
Non-trivial Selectors

$(“#menu > li:not(:first-child)”).hide();

$(“ul[ul]”).show();

$(“tr:even”).addClass(“even”);
Injecting HTML

• Very frustrating problem
• Browsers are very tempermental
• (Inserting table rows, select options, etc.)
HTML Solution

• Allow users to insert HTML strings
• Convert to DOM nodes on the fly
• Inject into the document correctly
$(“table tr”).append(“<td>test</td>”);
$(“select”).prepend(“<option>test</option>”);
• DOM Ready + Selectors + HTML Injection
• The dream of true unobtrusive DOM
   scripting

$(document).ready(function(){
    $(“select”).append(“<option>None</option>”);
});
New Expectations
• What new expectations emerge out of this
  new API?

 $(“ul > li”).click(function(){
   $(this).load(“menu.html”);
 });



 <ul>
   <li>item a</li>
   <li>item b</li>
 </ul>
The Perception

• When the document was ready:
 • We bound an event to a set of elements
• We loaded some new elements
 • Why don’t they have the event?
New Pattern: Behaviors
function handleClick() {
  $(“li”, this).click(loadMenu);
}

function loadMenu() {
  $(this).load(“menu.html”, handleClick);
}

$(document).ready(function(){
  $(document).each(handleClick);
});
Behaviors

$(document).ready(function(){
  $(“li”).behavior(“click”,function(){
    $(this).load(“menu.html”);
  });
});
Pure DOM
        function handleClick( elem ) {
           var li = elem.getElementsByTagName(“li”);
           for ( var i = 0; i < li.length; i++ )
               li[i].addEventListener( “click”, loadMenu, false );
Doesn’t exist in IE
        }

      function loadMenu() {         IE sets the wrong context
          var elem = this;
  Doesn’t exist in IE = new XMLHttpRequest();
          var xhr
          xhr.open( “GET”, “menu.html”, false );
          xhr.onreadystatechange = function(){                  Leaks in IE
             if ( xhr.readyState == 4 ) {
                 elem.innerHTML = xhr.responseText;
                 handleClick( elem );
             }
          };
          xhr.send( null );
      }

       window.onload = function(){      Doesn’t happen immediately
          var ul = document.getElementsByTagName(“ul”);
          for ( var i = 0; i < ul.length; i++ )
            handleClick( ul[i] );
       };
FUEL

• JavaScript Library for Firefox Extension
  Development
• Designed to be used by Web Developers
• Current API is very C++ centric
Mozilla: Preferences
var prefs = Components.classes["@mozilla.org/preferences-service;1"]
  .getService(Components.interfaces.nsIPrefBranch);

var str = Components.classes["@mozilla.org/supports-string;1"]
  .createInstance(Components.interfaces.nsISupportsString);
str.data = "some non-ascii text";
prefs.setComplexValue("preference.with.non.ascii.value",
      Components.interfaces.nsISupportsString, str);
Preferences w/ FUEL

Application.prefs.setValue(“some.pref”, “some non-ascii text”);
SELECT * FROM users WHERE id = 5;

        SQL




                       $res = mysql_query(“SELECT * FROM users WHERE id = 5;”);
Programming Language   while ( $row = mysql_fetch_assoc($res) ) {
                         // etc.
      Interface        }




                       User.find(5)
     Abstraction
    Layer (ORM)
class Account < ActiveRecord::Base
    has_many :people do
      def find_or_create_by_name(name)
        first_name, last_name = name.split(" ", 2)
        find_or_create_by_first_name_and_last_name
(first_name, last_name)
      end
    end
  end

  person = Account.find(:first).people
    .find_or_create_by_name("David Heinemeier Hansson")
  person.first_name # => "David"
  person.last_name # => "Heinemeier Hansson"
Conclusion

• Libraries build new patterns on top of
  existing APIs
• New library patterns advance development
  in meaningful, considerable, ways
Bonus: Meta-Libraries

• Domain Specific Languages (DSLs)
• Build upon existing libraries building new
  languages out of their APIs
• “jQuery2” meta language:
  http://ejohn.org/apps/jquery2/
More info...
• http://ejohn.org/
• http://jquery.com/
• http://wiki.mozilla.org/FUEL
• http://ejohn.org/apps/jquery2/

• Contact:
  jeresig@gmail.com

More Related Content

What's hot

Working with the django admin
Working with the django admin Working with the django admin
Working with the django admin flywindy
 
Modern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsModern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsMike North
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDCMike Dirolf
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuerycolinbdclark
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングscalaconfjp
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery EssentialsMark Rackley
 
Elasticsearch for SQL Users
Elasticsearch for SQL UsersElasticsearch for SQL Users
Elasticsearch for SQL UsersAll Things Open
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developerSalvatore Fazio
 
MongoDB & NoSQL 101
 MongoDB & NoSQL 101 MongoDB & NoSQL 101
MongoDB & NoSQL 101Jollen Chen
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript MisunderstoodBhavya Siddappa
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
How to make Ajax Libraries work for you
How to make Ajax Libraries work for youHow to make Ajax Libraries work for you
How to make Ajax Libraries work for youSimon Willison
 
Coding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerCoding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerMatthew Farwell
 
Scaladays 2014 introduction to scalatest selenium dsl
Scaladays 2014   introduction to scalatest selenium dslScaladays 2014   introduction to scalatest selenium dsl
Scaladays 2014 introduction to scalatest selenium dslMatthew Farwell
 

What's hot (20)

Working with the django admin
Working with the django admin Working with the django admin
Working with the django admin
 
Modern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsModern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.js
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuery
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Elasticsearch for SQL Users
Elasticsearch for SQL UsersElasticsearch for SQL Users
Elasticsearch for SQL Users
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
End-to-end testing with geb
End-to-end testing with gebEnd-to-end testing with geb
End-to-end testing with geb
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
 
MongoDB & NoSQL 101
 MongoDB & NoSQL 101 MongoDB & NoSQL 101
MongoDB & NoSQL 101
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
How to make Ajax Libraries work for you
How to make Ajax Libraries work for youHow to make Ajax Libraries work for you
How to make Ajax Libraries work for you
 
Coding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerCoding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checker
 
Scaladays 2014 introduction to scalatest selenium dsl
Scaladays 2014   introduction to scalatest selenium dslScaladays 2014   introduction to scalatest selenium dsl
Scaladays 2014 introduction to scalatest selenium dsl
 

Viewers also liked

High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010Nicholas Zakas
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Nicholas Zakas
 
Modern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsModern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsVolodymyr Voytyshyn
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 

Viewers also liked (6)

High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
 
php
phpphp
php
 
Modern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsModern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design Patterns
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 

Similar to Advancing JavaScript with Libraries (Yahoo Tech Talk)

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)jeresig
 
JS Libraries and jQuery Overview
JS Libraries and jQuery OverviewJS Libraries and jQuery Overview
JS Libraries and jQuery OverviewAleksandr Motsjonov
 
Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQueryGill Cleeren
 
J query presentation
J query presentationJ query presentation
J query presentationakanksha17
 
J query presentation
J query presentationJ query presentation
J query presentationsawarkar17
 
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONAn introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONSyed Moosa Kaleem
 
Intro JavaScript
Intro JavaScriptIntro JavaScript
Intro JavaScriptkoppenolski
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Dutyreedmaniac
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyLeslie Doherty
 
ITFT - Java Coding
ITFT - Java CodingITFT - Java Coding
ITFT - Java CodingBlossom Sood
 
CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11virtualsciences41
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseSpeedment, Inc.
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSpeedment, Inc.
 

Similar to Advancing JavaScript with Libraries (Yahoo Tech Talk) (20)

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)
 
JS Libraries and jQuery Overview
JS Libraries and jQuery OverviewJS Libraries and jQuery Overview
JS Libraries and jQuery Overview
 
Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQuery
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
J query presentation
J query presentationJ query presentation
J query presentation
 
J query presentation
J query presentationJ query presentation
J query presentation
 
JS Essence
JS EssenceJS Essence
JS Essence
 
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONAn introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
 
Intro JavaScript
Intro JavaScriptIntro JavaScript
Intro JavaScript
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Duty
 
presentation
presentationpresentation
presentation
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Duty
 
presentation
presentationpresentation
presentation
 
ITFT - Java Coding
ITFT - Java CodingITFT - Java Coding
ITFT - Java Coding
 
CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your database
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your database
 
06.1 .Net memory management
06.1 .Net memory management06.1 .Net memory management
06.1 .Net memory management
 

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 Librarianjeresig
 
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 Investigationjeresig
 
Hacking Art History
Hacking Art HistoryHacking Art History
Hacking Art Historyjeresig
 
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 Academyjeresig
 
Applying Computer Vision to Art History
Applying Computer Vision to Art HistoryApplying Computer Vision to Art History
Applying Computer Vision to Art Historyjeresig
 
NYARC 2014: Frick/Zeri Results
NYARC 2014: Frick/Zeri ResultsNYARC 2014: Frick/Zeri Results
NYARC 2014: Frick/Zeri Resultsjeresig
 
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 Analysisjeresig
 
Applying Computer Vision to Art History
Applying Computer Vision to Art HistoryApplying Computer Vision to Art History
Applying Computer Vision to Art Historyjeresig
 
JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)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 Mobilejeresig
 
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 Performancejeresig
 
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
 

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
 
JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)
 
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)
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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 textsMaria Levchenko
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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)wesley chun
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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 CVKhem
 
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?Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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)
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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?
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

Advancing JavaScript with Libraries (Yahoo Tech Talk)

  • 1. Advancing JavaScript with Libraries John Resig ejohn.org / jquery.com / mozilla.com
  • 2. Two Hats • Mozilla Corp • jQuery JavaScript Library • FUEL • Released Jan 2006 • JS Lib for Ext. Devs • Small Filesize • Reduce Complexity • Short, concise, code • JS Lib Test Suites • Extensible via plugins • Integration, better coverage
  • 3. Libraries are... • ...abstractions away from existing APIs • ...giving us new APIs to interface with
  • 4. Hypothesis • APIs breed patterns • Libraries build new patterns on top of existing APIs • New library patterns advance development in meaningful, considerable, ways
  • 5. Why Create A Library? • Distance ourselves from repetition • In JavaScript: • Distance from browser differences • In C (stdlib): • Distance from platform differences
  • 6. DOM API • Implemented in every modern browser • Most stable of all the JavaScript APIs • Very well documented
  • 7. Fails in IE 7 JavaScript: document.getElementById(“obj”) .getElementsByTagName(“*”) HTML: <object id=”obj”> <param name="src" value="test.mov"/> <param name="title" value="My Video"/> </object>
  • 8. Fails in Safari 2 JavaScript: document.getElementById(“opt”).selected HTML: <div style=”display: none;”> <select><option id=”opt” value=”test”/></select> </div>
  • 10. Fails in Opera & IE JavaScript: document.getElementById(“q”) HTML: <form action="" method="POST"> <input type="text" name="q"/> <span id="q">Search</span> </form>
  • 11. Fails in Opera & IE JavaScript: var f = document.getElementsByTagName(“input”); for ( var i = 0; i < f.length; i++ ) { ... } HTML: <form action="" method="POST"> Num Rows: <input type="text" id="length" value="22"/><br/> <input type="submit" value="Generate"/> </form>
  • 12. Re-interpretation of the Spec
  • 13. Fails in All JavaScript: document.getElementById(“name”) .setAttribute(“disabled”, false); HTML: <input type=”text” id=”name” disabled=”disabled”/>
  • 16. Why are Libraries Created? • Browsers have a large number of strange differences... • IE has a lot of well documented bugs • Safari has less, but more obscure, bugs • APIs don’t do what you expect • When the API is impossible to learn, but through experience
  • 17. Break down into Meta-Problems • Waiting for the document to load • Traversing the DOM • Injecting HTML into a page
  • 18. Waiting for the DOM to load • A DOM document must be fully loaded before you can work with it • Waiting for the window to load causes flashes of un-effected content
  • 19. Focusing an input <input type=”text” id=”test”/> <script>document.getElementById(“test”).focus();</script> <head><script src=”script.js”</head> $(document).ready(function(){ $(“#test”).focus(); });
  • 20. Traversing the DOM • getElementsByTagName, getElementById, getAttribute, nextSibling, previousSibling, parentNode, className, etc. • A lot to learn and get right • Has the potential to be very tricky (and long-winded)
  • 21. DOM Selectors • Goal: Improve the DOM Traversal API • Provide an API on top of the existing DOM API • Look to standards for inspiration
  • 22. Types of Selectors • XPath Selectors • //div/span[2] • /html[@id=’home’] • CSS 3 Selectors • div > span:nth-of-type(2) • html:root#home
  • 23. Non-trivial Selectors $(“#menu > li:not(:first-child)”).hide(); $(“ul[ul]”).show(); $(“tr:even”).addClass(“even”);
  • 24. Injecting HTML • Very frustrating problem • Browsers are very tempermental • (Inserting table rows, select options, etc.)
  • 25. HTML Solution • Allow users to insert HTML strings • Convert to DOM nodes on the fly • Inject into the document correctly $(“table tr”).append(“<td>test</td>”); $(“select”).prepend(“<option>test</option>”);
  • 26. • DOM Ready + Selectors + HTML Injection • The dream of true unobtrusive DOM scripting $(document).ready(function(){ $(“select”).append(“<option>None</option>”); });
  • 27. New Expectations • What new expectations emerge out of this new API? $(“ul > li”).click(function(){ $(this).load(“menu.html”); }); <ul> <li>item a</li> <li>item b</li> </ul>
  • 28. The Perception • When the document was ready: • We bound an event to a set of elements • We loaded some new elements • Why don’t they have the event?
  • 29. New Pattern: Behaviors function handleClick() { $(“li”, this).click(loadMenu); } function loadMenu() { $(this).load(“menu.html”, handleClick); } $(document).ready(function(){ $(document).each(handleClick); });
  • 31. Pure DOM function handleClick( elem ) { var li = elem.getElementsByTagName(“li”); for ( var i = 0; i < li.length; i++ ) li[i].addEventListener( “click”, loadMenu, false ); Doesn’t exist in IE } function loadMenu() { IE sets the wrong context var elem = this; Doesn’t exist in IE = new XMLHttpRequest(); var xhr xhr.open( “GET”, “menu.html”, false ); xhr.onreadystatechange = function(){ Leaks in IE if ( xhr.readyState == 4 ) { elem.innerHTML = xhr.responseText; handleClick( elem ); } }; xhr.send( null ); } window.onload = function(){ Doesn’t happen immediately var ul = document.getElementsByTagName(“ul”); for ( var i = 0; i < ul.length; i++ ) handleClick( ul[i] ); };
  • 32. FUEL • JavaScript Library for Firefox Extension Development • Designed to be used by Web Developers • Current API is very C++ centric
  • 33. Mozilla: Preferences var prefs = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch); var str = Components.classes["@mozilla.org/supports-string;1"] .createInstance(Components.interfaces.nsISupportsString); str.data = "some non-ascii text"; prefs.setComplexValue("preference.with.non.ascii.value", Components.interfaces.nsISupportsString, str);
  • 35. SELECT * FROM users WHERE id = 5; SQL $res = mysql_query(“SELECT * FROM users WHERE id = 5;”); Programming Language while ( $row = mysql_fetch_assoc($res) ) { // etc. Interface } User.find(5) Abstraction Layer (ORM)
  • 36. class Account < ActiveRecord::Base has_many :people do def find_or_create_by_name(name) first_name, last_name = name.split(" ", 2) find_or_create_by_first_name_and_last_name (first_name, last_name) end end end person = Account.find(:first).people .find_or_create_by_name("David Heinemeier Hansson") person.first_name # => "David" person.last_name # => "Heinemeier Hansson"
  • 37. Conclusion • Libraries build new patterns on top of existing APIs • New library patterns advance development in meaningful, considerable, ways
  • 38. Bonus: Meta-Libraries • Domain Specific Languages (DSLs) • Build upon existing libraries building new languages out of their APIs • “jQuery2” meta language: http://ejohn.org/apps/jquery2/
  • 39. More info... • http://ejohn.org/ • http://jquery.com/ • http://wiki.mozilla.org/FUEL • http://ejohn.org/apps/jquery2/ • Contact: jeresig@gmail.com