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

Mais conteúdo relacionado

Mais procurados

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
 

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

Destaque

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
 

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

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

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

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

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

Último

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Último (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

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