SlideShare ist ein Scribd-Unternehmen logo
1 von 134
Downloaden Sie, um offline zu lesen
How to
make
                        work
                         for you
Simon Willison - http://simonwillison.net/
      Web 2.0 Expo Berlin
         5th November 2007
In this talk
• Where Ajax came from
• When you should (and shouldn’t) use it
• Ajax fundamentals (including a DOM and
  JavaScript refresher)
• Advanced Ajax techniques
• Picking and using a JavaScript library
Please ask
 questions
at any time
February 2005
AJAX v.s. Ajax
  “Asynchronous
JavaScript + XML”
AJAX v.s. Ajax
                    “Any technique that
  “Asynchronous
                     allows the client to
JavaScript + XML”
                     retrieve more data
                       from the server
                    without reloading the
                         whole page”
Why did Ajax happen?

•   Two reasons:

    •   The browsers that mattered all added support
        for IE’s XMLHttpRequest object (which IE has
        had since 1998)

    •   Jesse James Garrett came up with a name that
        sucked a lot less than “XMLHttpRequest” did
Pre-Ajax...
• “Remote Scripting” (not as catchy)
• Various unpleasant but ingenious hacks:
 • Scriptable Java applets
 • Passing data through changes to a cookie
 • Passing data through a hidden iframe
   • (That one’s actually still in use)
Ajax scenarios
How to make Ajax work for you
How to make Ajax work for you
How to make Ajax work for you
How to make Ajax work for you
How to make Ajax work for you
How to make Ajax work for you
How to make Ajax work for you
How to make Ajax work for you
How to make Ajax work for you
How to make Ajax work for you
Some anti-patterns

• Drag and drop shopping carts
• Massive page updates e.g. pagination
• Unlinkable content (see also bookmarking)
• Breaking browser expectations
• Forgetting the loading icon!
Fundamentals
The three legged stool




           (X)HTML
     CSS             JavaScript
The three legged stool

           The DOM




           (X)HTML
     CSS             JavaScript
The DOM
The DOM
The DOM

                <html>

<head>               <body>

<title>   <div id=quot;headquot;> <div id=quot;mainquot;>

              <h1>       <p>   <p>    <p>
Key DOM methods
   • document.getElementsByTagName,
      document.getElementById
   • el.childNodes, el.parentNode, el.firstChild,
      el.nextSibling, el.getAttribute
   • el.appendChild, el.insertBefore,
      el.setAttribute, el.removeChild
   • document.createElement,
      document.createTextNode
http://www.howtocreate.co.uk/tutorials/javascript/domstructure
JavaScript doesn’t suck!

• Just remember; your; semicolons;
• Avoid accidental globals: always declare your
  variables with “var”
• Take the time to figure out higher order
  programming, where you treat functions as
  objects
CSS class switching

• Often if you are dynamically making large-
  scale changes to the layout of a page...
• ... you can do most of the work by defining
  an alternative CSS class ...
• ... and then switching a container element’s
  className property in your JavaScript
Firebug!
Firebug
•   Inspect HTML elements to see what CSS
    rules currently apply to them
•   Interactive console for experimenting with
    JavaScript against the loaded page
•   Full JavaScript debugger, including breakpoints
•   Profile your code and your site’s assets and
    Ajax requests
•   Logging with console.log() and friends
XMLHttpRequest

• The object that lets you make HTTP
  requests from within JavaScript
• IE had it first, using an ActiveX Object
• Almost nothing to do with XML
• Asynchronous (so you use callbacks)
XMLHttpRequest

• The object that lets you make HTTP
  requests from within JavaScript
• IE had it first, using an ActiveX Object
• Almost nothing to do with XML
• Asynchronous (so you use callbacks)
var xhr = createXHR();
    xhr.onreadystatechange = onComplete;
    xhr.open('GET', '/helloworld.txt', true);
    xhr.send(null);

function onComplete() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            alert(xhr.responseText);
        } else {
            alert('Error code ' + xhr.status);
        }
    }
}
var xhr = createXHR();
xhr.onreadystatechange = onComplete;
xhr.open('GET', '/helloworld.txt', true);
xhr.send(null);

function onComplete() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            alert(xhr.responseText);
        } else {
            alert('Error code ' + xhr.status);
        }
    }
}
var xhr = createXHR();
xhr.onreadystatechange = onComplete;
xhr.open('GET', '/helloworld.txt', true);
xhr.send(null);

function onComplete() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            alert(xhr.responseText);
        } else {
            alert('Error code ' + xhr.status);
        }
    }
}
var xhr = createXHR();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            alert(xhr.responseText);
        } else {
            alert('Error code ' + xhr.status);
        }
    }
};
xhr.open('GET', '/helloworld.txt', true);
xhr.send(null);
function createXHR() {
    var xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e) {}
    }
    return xhr;
}
function createXHR() {
    var xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {}
    }
    return xhr;
}
var xhr = createXHR();
xhr.onreadystatechange = onComplete;
xhr.open('POST', '/helloworld.php', true);
xhr.setRequestHeader(
    'Content-Type',
    'application/x-www-form-urlencoded'
);
xhr.send('name=Simon&age=26');
xhr.open('POST', '/helloworld.php', true);


The third argument specifies that we want to
make an asynchronous request (“tell me
when you’re done by calling this function”). If
you set this to false you’ll get a synchronous
request, which will completely hang the
browser until the request returns.

                Don’t do that.
Too much boilerplate?

• That’s quite a lot to remember
• Best option: don’t remember any of it!
• Use a good library instead
• Lots more on those later on
doRequest
doRequest(quot;GETquot;, quot;/blah.txtquot;, null, function(xhr) {
    doSomethingWith(xhr.responseText);
});

doRequest(quot;GETquot;, quot;/getinfo.phpquot;, {
    quot;namequot;: quot;Simonquot;
  }, function(xhr) {
    doSomethingWith(xhr.responseText);
});

doRequest(quot;POSTquot;, quot;/getinfo.phpquot;, {
    quot;namequot;: quot;Simonquot;
  }, function(xhr) {
    doSomethingWith(xhr.responseText);
});
function doRequest(method, url, args, callback) {
    var xhr = createXHR();
    method = method.toUpperCase();
    args = args && buildQueryString(args);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            callback(xhr);
        }
    };
    if (method == 'GET' && args) {
        url += '?' + args;
        args = null;
    }
    xhr.open(method, url, true);
    if (method == 'POST') {
        xhr.setRequestHeader(
            'Content-Type',
            'application/x-www-form-urlencoded'
        );
    }
    xhr.send(args);
}
function buildQueryString(obj) {
    var bits = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            bits[bits.length] = escape(key) + '=' +
            escape(obj[key]);
        }
    }
    return bits.join('&');
}

var s = buildQueryString({
    name: 'Simon',
    age: 26
});

name=Simon&age=26
Data transport options
Client data submission
• Requests can have anything you like in the
  body:
  • HTML, XML, JSON...
• So if you really want to, you can access
  SOAP or XML-RPC services from JavaScript
• For almost all purposes, regular form
  arguments suffice
• REST APIs are a good fit as well
Server responses
• Plain text
• HTML fragments
• CSV or similar
• XML
• Executable JavaScript
• JSON
Plain text
• Just sending back a simple value
 • xhr.responseText is all you need
• Pros:
 • Absurdly simple
• Cons:
 • Only supports a single value or string
HTML fragments
• Return an HTML fragment, and inject it using
  innerHTML
  function onSuccess(xhr) {
    var div = document.getElementById('response');
    div.innerHTML = xhr.responseText;
  }

  <div id=quot;responsequot;>
  </div>
Fragment pros and cons
•   Pros:

    •   Again, really simple

    •   You can leverage existing server-side templates
        and techniques

•   Cons:

    •   You have to change your server-side code to
        change client-side behaviour

    •   You can't reuse your endpoint
Executable JavaScript
• We can pass JavaScript code back from
  the server and execute it directly

  document.getElementById(
     'response').innerHTML = 'Done!';




  function onSuccess(o) {
    eval(o.responseText);
  }
•   Pros:
    •   Incredibly simple client-side code
    •   The server can do abolutely anything, without
        needing to modify the client-side code
•   Cons:
    •   Weird factoring of code - dynamically
        generating code to run on the client makes it
        hard to keep track of the big picture
•   How about just sending structured data?
CSV or similar
• We want structured data!
  Simon Willison,26,simon@simonwillison.net

• Pros:
 • Easy to parse: xhr.responseText.split(',');
• Cons:
 • How do we pass values containing commas?
 • Index based, so brittle and hard to maintain
XML
• Surely XML will save us!
<person>
  <name>Simon</name>
  <age>26</age>
</person>

function onSuccess(xhr) {
    var dom = xhr.responseXML;
    showPerson(
      dom.getElementsByTagName('name')[0].data,
      parseInt(dom.getElementsByTagName('age')[0].data, 10)
    });
}
XML pros and cons
• Pros:
 • We can re-use our DOM knowledge
 • xhr.responseXML parses it for us
 • We can call existing Web Services directly
• Cons:
 • Verbose handling code
 • Is this the simplest thing that could
    possibly work?
JSON
• A standard for representing common data
  structures, quot;discoveredquot; by Douglas
  Crockford
• Common data structures?
 • Associative arrays (dictionaries / hashes)
 • Arrays (lists)
 • Numbers, strings, booleans
• A subset of JavaScript syntax
JSON example

{quot;namequot;: quot;Simonquot;, quot;agequot;: 26}

function onSuccess(xhr) {
    var person = eval('(' + xhr.responseText + ')')
    ...
)
More complex JSON
{quot;peoplequot;: [{
     quot;namequot;: quot;Simonquot;,
     quot;emailquot;: quot;simon@simonwillison.netquot;
   }, {
     quot;namequot;: quot;Nataliequot;,
     quot;emailquot;: quot;nat@natbat.netquot;
   }
]}

function onSuccess(xhr) {
  var people = eval('(' + xhr.responseText + ')');
  ...
}
To compare...
<people>
  <person>
    <name>Simon</name>
    <email>simon@simonwillison.net</email>
  </person>
  <person>
    <name>Natalie</name>
    <email>nat@natbat.net</email>
  </person>
</people>
To compare...
function onSuccess(o) {
  var dom = o.responseXML;
  var people = [];
  var people_els = dom.getElementsByTagName('people');
  for (var i = 0, el; el = people_els[i]; i++) {
    people[people.length] = {
       'name': el.getElementsByTagName('name')[0].data,
       'email': el.getElementsByTagName('email')[0].data
    };
  }
  ...
}
JSON v.s. XML

                               JSON       XML
Bytes (excluding whitespace)      95        156
  Lines of code to process            1     7+
It ain’t just for JavaScript
•   Libraries for consuming and generating JSON
    are available for many languages, including:

    •   Python

    •   Ruby

    •   PHP

    •   Java ...

    •   JSON works really well as a general purpose
        tool for exchanging data structures
Aside: XSLT

• Modern browsers support XSLT transforms
  - albeit with differing APIs
• These can be significantly faster than regular
  DOM manipulation
• If you're having performance problems, this
  may be worth looking in to
Recommendations
• For quick and simple apps, HTML fragments
  offer the path of least resistance
• For most purposes, JSON makes the most
  sense
• Use XML if you already have an XML Web
  Service that you want to consume (or you
  need an XSLT speed boost)
Let’s see some
 running code
Advanced Ajax topics
Cross-domain Ajax
The same-origin restriction

• XMLHttpRequest is only allowed to
  communicate with the domain from which
  the page was loaded
• The same is true of JavaScript calls between
  windows, frames and iframes
• This is a critical browser security feature
The intranet attack

• http://wiki.private.corp/ contains private data
• User is tricked in to visiting evilexample.com
• evilexample.com uses XMLHttpRequest (or
  a hidden iframe child) to load and steal data
  from http://wiki.private.corp/
• JSON-P offers a (hackish) solution to the
          cross-domain XMLHttpRequest restriction
http://example.com/query?name=Simon

callback({quot;namequot;: quot;Simonquot;, quot;agequot;: 26});

function loadJSON(url) {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;
  document.getElementsByTagName('head')[0].appendChild(script);
}

function callback(person) {
  ...
}

loadJSON('http://example.com/query?name=' + name);
• JSON-P offers a (hackish) solution to the
          cross-domain XMLHttpRequest restriction
http://example.com/query?name=Simon

callback({quot;namequot;: quot;Simonquot;, quot;agequot;: 26});

function loadJSON(url) {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;
  document.getElementsByTagName('head')[0].appendChild(script);
}

function callback(person) {
  ...
}

loadJSON('http://example.com/query?name=' + name);
Pros and cons
•   Pros:

    •   Lets you call services hosted on other domains,
        provided they opt-in

        •   del.icio.us, Flickr, other sites offer this

•   Cons:

    •   Detecting errors is harder than with
        XMLHttpRequest

    •   You have to trust the site who’s code you are
        executing
XSS
• XSS attacks occur when a malicious third
  party injects untrusted code (HTML, CSS or
  JavaScript) in to your page

• It’s generally a server-side consideration, but
  you need to take it in to consideration when
  writing JavaScript as well

• Ajax can compound the problem by allowing
  users to create self-propagating “worms”
CSRF
CSRF for GET
<img src=quot;http://example.com/admin/delete.php?id=5quot;>


Trick someone who is signed in to
example.com/admin/ in to visiting a page
hosting that image and you’ll force them to
delete something.
CSRF for POST
<form id=quot;evilquot;
 action=quot;http://example.com/admin/delete.phpquot;
 method=quot;POSTquot;>
  <input type=quot;hiddenquot; name=quot;idquot; value=quot;5quot;>
</form>
<script>
document.getElementById('evil').submit()
</script>
CSRF protection
• For regular forms, add a hidden field with a
  one-time secret token and check for that
  token on every submission
• For Ajax, either do the above or use:
  xhr.setRequestHeader(
      quot;X-Requested-Withquot;, quot;XMLHttpRequestquot;
  );
Unobtrusive JavaScript
Unobtrusive JavaScript
• JavaScript isn't always available
 • Security conscious organisations (and
    users) sometimes disable it
  • Some devices may not support it (mobile
    phones for example)
  • Assistive technologies (screen readers)
    may not play well with it
  • Search engine crawlers won't execute it
• Unobtrusive: stuff still works without it!
Progressive enhancement
• Start with solid markup
• Use CSS to make it look good
• Use JavaScript to enhance the usability of the
  page


• The content remains accessible no matter
  what
Adding events
   • Unobtrusive JavaScript relies on adding event
      handlers after the fact
   • The naive way of doing this:
window.onload = function() {
   for (var i = 0, link; link = document.links[i]; i++) {
     if (link.className == 'external') {
       link.onclick = function() {
         window.open(this.href);
         return false;
       }
     }
   }
};
Problem
• If you later assign something else to
  window.onload (or one of the link.onclicks)
  you will clobber your behaviour
• You should add events quot;properlyquot;...
 • Different in different browsers
   • attachEvent v.s. addEventListener
 • My advice: use a library!
Unobtrusive examples
labels.js




• One of the earliest examples of this
  technique, created by Aaron Boodman (now
  of Greasemonkey and Google Gears fame)
How to make Ajax work for you
How to make Ajax work for you
How it works
         <label for=quot;searchquot;>Search</label>
         <input type=quot;textquot; id=quot;searchquot; name=quot;qquot;>

• Once the page has loaded, the JavaScript:
 • Finds any label elements linked to a text field
 • Moves their text in to the associated text field
 • Removes them from the DOM
 • Sets up the event handlers to remove the
    descriptive text when the field is focused
• Clean, simple, reusable
easytoggle.js
  • An unobtrusive technique for revealing
     panels when links are clicked

<ul>
  <li><a href=quot;#panel1quot; class=quot;togglequot;>Panel 1</a></li>
  <li><a href=quot;#panel2quot; class=quot;togglequot;>Panel 2</a></li>
  <li><a href=quot;#panel3quot; class=quot;togglequot;>Panel 3</a></li>
</ul>


<div id=quot;panel1quot;>...</div>
<div id=quot;panel2quot;>...</div>
<div id=quot;panel3quot;>...</div>
How to make Ajax work for you
How to make Ajax work for you
How it works
•   When the page has loaded...

    •   Find all links with class=quot;togglequot; that reference an
        internal anchor

    •   Collect the elements that are referenced by those
        anchors

    •   Hide all but the first

    •   Set up event handlers to reveal different panels when a
        link is clicked

•   Without JavaScript, links still jump to the right point
Django filter lists

• Large multi-select boxes aren't much fun
 • Painful to scroll through
 • Easy to lose track of what you have
    selected
• Django's admin interface uses unobtrusive
  JavaScript to improve the usability here
How to make Ajax work for you
How to make Ajax work for you
• Ajax is often used to avoid page refreshes
• So...
 • Write an app that uses full page refreshes
 • Use unobtrusive JS to quot;hijackquot; links and
    form buttons and use Ajax instead

• Jeremy Keith coined the term quot;Hijaxquot; to
  describe this
More progressive Ajax
     suggestions
• Live search / filtering
• Adding comments / tags
• Smart form validation
• Checking if usernames are already taken
• You could even make a progressively
  enhanced chat room
The onload problem
• All of these examples use code that runs
  when the window quot;loadquot; event is fired
  • Wait until page is loaded, then manipulate
     the DOM
• Problem: If the page takes a while to load
  (large inline images) there will be a Flash Of
  Unstyled Content (FOUC)
• Also, if the user clicks things before the
  setup code has fired they won't get the
  expected behaviour.
document.write(css)

• If the effect requires hiding some otherwise
  visible elements, you can document.write a
  stylesheet

  <script type=quot;text/javascriptquot;>
  document.write('<style type=quot;text/cssquot;>';
  document.write('.hideme { display: none }');
  document.write('</style>');
  </script>
body.onclick

• If your effect is triggered by the user clicking on
  something, attach code to the document.body quot;clickquot;
  event right at the start of your code (no need to wait
  for the document quot;loadquot; event)

  YAHOO.util.Event.on(document.body, 'click' function(e) {
    var clicked_el = YAHOO.util.Event.getTarget(e);
    // ...
  }
onDOMReady
•   A number of attempts have been made to create
    an onDOMReady event that fires when the
    DOM has been constructed but before the page
    has loaded

    •   dean.edwards.name/weblog/2006/06/again/

    •   Modern libraries all support this in some form

•   Problem: CSS may not have loaded, so calculated
    dimensions may be incorrect
• Unobtrusive JavaScript is the Right Way to
  go about things, but runs in to browser
  differences even faster than regular
  JavaScript

• Which leads us neatly on to...
Frameworks and
   Libraries
JavaScript libraries

•   ajaxpatterns.org lists over 40 general purpose
    JavaScript libraries

    •   ... and that’s not including the many libraries tied
        to a specific server-side language

•   Why are there so many of them?
“The bad news:
JavaScript is broken.
    The good news:
 It can be fixed with
  more JavaScript!”
              Geek folk saying
•   Inconsistent event model (thanks, IE)
•   Positioning and co-ordinates
•   Memory management (thanks, IE)
•   The DOM is a horrible API!
•   JavaScript-the-language has quite a few warts
    •   But it’s powerful enough to let you fix them
•   Classes and inheritance can be confusing
•   Many useful JS utility functions are missing
•   Drag and drop and Animation are really hard
Narrowing them down...

• Prototype (and Scriptaculous)
• The Yahoo! User Interface Library - YUI
• jQuery
• The Dojo Toolkit
Honourable mentions
•   MochiKit

    •   No updates since early 2006

•   The Google Web Toolkit

    •   I don’t do Java

•   mooTools

    •   Lots of buzz, but I haven’t figured out why yet
Download
                                                            Get the latest version—1.5.1


                                                            Learn
Prototype is a JavaScript Framework that aims to            Online documentation and resources.
ease development of dynamic web applications.

                                                            Discuss
Featuring a unique, easy-to-use toolkit for class-driven
development and the nicest Ajax library around, Prototype   Mailing list and IRC
is quickly becoming the codebase of choice for web
application developers everywhere.
                                                            Contribute
                                                            Submit patches and report bugs.


   Prototype and Scriptaculous
Prototype and script.aculo.us: The quot;Bungee
bookquot; has landed!                                           Who's using Prototype?
                                                            Meet the developers
                    Core team member Christophe
                    Porteneuve has been hard at work
                    for the past few months tracking
• Prototype focuses on basic browser
  compatibility and JavaScript language
  enhancement

• Tries to make JavaScript more like Ruby
• Extends most of JavaScript’s built-in objects
  with new functionality

• Scriptaculous adds fancy effects, basic
  widgets and drag and drop
$$('#bmarks li').each(function(li){
  Event.observe(li, 'click', function(e) {
    this.style.backgroundColor = 'yellow';
  }.bindAsEventListener(li));
});
The Yahoo UI Library
• Created at Yahoo!, BSD licensed
• Designed for both creating new applications
  and integration with legacy code

• Focused on browser issues; almost no
  functionality relating to JS language itself

• Extensively tested and documented
controls

                  calendar        container
autocomplete


  menu           slider          treeview



                             dragdrop
    animation


  dom           event           connection

                utilities
YAHOO.util.Event.on(window, 'load', function() {
	

 var div = YAHOO.util.Dom.get('messages');
	

 setTimeout(function() {
	

 	

 var anim = new YAHOO.util.Anim(div, {
	

 	

 	

 height: {to: 0},
	

 	

 	

 opacity: {to: 0}
	

 	

 }, 0.4);
	

 	

 anim.animate();
	

 	

 anim.onComplete.subscribe(function() {
	

 	

 	

 div.parentNode.removeChild(div);
	

 	

 });
	

 }, 2000);
});
Common YUI idiom

$E = YAHOO.util.Event;
$D = YAHOO.util.Dom;

$E.on(window, 'load', function() {
	

 var div = $D.get('messages');
     ...
});
jQuery
jQuery(function($) {
    $(quot;a.hidemequot;).
        css('color', 'red').
        click(function() {
            $(this).hide(quot;slowquot;);
            return false;
        });
});
•   Simple philosophy: find some nodes, then do
    something to them

•   Minimal impact on your global namespace - it adds
    two global symbols: jQuery and $, and $ can be easily
    reverted

•   API designed around “chaining” - other libraries are
    now emulating this

•   Outstanding node selection, based on CSS 3 and
    custom extensions

•   Small core library with an intelligent plugin
    mechanism
Dojo
• The oldest of the current popular libraries,
  pre-dating even Ajax

• Incredible amounts of functionality
• Used to suffer from a tough learning curve,
  although the 0.9 release simplifies things
  greatly
Dojo components
• dojo
 • Core library, similar to jQuery etc
 • Smart package managment with dynamic
    code loading
• dijit
 • Advanced widget system
• dojox
 • Dojo eXperimental - crazy voodoo magic
dijit
How to make Ajax work for you
div dojoType=quot;dijit.layout.TabContainerquot; sizeShare=quot;40quot;
div id=quot;tab1quot;
 dojoType=quot;dijit.layout.ContentPanequot; title=quot;Form Feelquot;
  h2Various Form Elements:/h2
    form name=quot;dijitFormTestquot;
pinput type=quot;checkBoxquot;
     dojoType=quot;dijit.form.CheckBoxquot; checked=quot;checkedquot;
Standard Dijit CheckBox
brinput type=quot;checkBoxquot;
     dojoType=quot;dijit.form.CheckBoxquot; disabled=quot;disabledquot;
Disabled Dijit
br
input type=quot;checkBoxquot;
     dojoType=quot;dijit.form.CheckBoxquot; disabled=quot;disabledquot;
    checked=quot;checkedquot;
Checked and Disabled Dijit
/p
...
dojox
• Graphics (cross-browser drawing API)
• Offline storage
• Cryptography
• Templating
• Data grids and more
• “The future of the browser today”
How to make Ajax work for you
My library selection criteria

• Enables unobtrusive JavaScript
• Plays well with other code
 • Smart use of namespacing
 • Global variable impact kept to a minimum
• Tie breaker: the less code I have to write the
  better!
• I’m currently using and recommending
  jQuery for most situations

• But... there’s cut-throat competition
  between the various libraries at the moment

• This is one of the reasons I care about
  interoperability - commit to a single library
  and you might lose out when one of the
  others jumps ahead of it
The law of leaky abstractions
http://www.joelonsoftware.com/articles/LeakyAbstractions.html


My interpretation:


        The more you rely on
   abstractions, the worse off you’ll
     be when one of them leaks
Thank you!

Weitere ähnliche Inhalte

Was ist angesagt?

Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJRealize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJLeonardo Balter
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsSiarhei Barysiuk
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)Nicholas Zakas
 
Don't make me wait! or Building High-Performance Web Applications
Don't make me wait! or Building High-Performance Web ApplicationsDon't make me wait! or Building High-Performance Web Applications
Don't make me wait! or Building High-Performance Web ApplicationsStoyan Stefanov
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSHannes Hapke
 
HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs SilverlightMatt Casto
 
Mobile HTML, CSS, and JavaScript
Mobile HTML, CSS, and JavaScriptMobile HTML, CSS, and JavaScript
Mobile HTML, CSS, and JavaScriptfranksvalli
 
Building an HTML5 Video Player
Building an HTML5 Video PlayerBuilding an HTML5 Video Player
Building an HTML5 Video PlayerJim Jeffers
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup PerformanceJustin Cataldo
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010Nicholas Zakas
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Libraryjeresig
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup PerformanceGreg Whalin
 
Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceNicholas Zakas
 

Was ist angesagt? (20)

Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJRealize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
 
What is HTML 5?
What is HTML 5?What is HTML 5?
What is HTML 5?
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
 
Don't make me wait! or Building High-Performance Web Applications
Don't make me wait! or Building High-Performance Web ApplicationsDon't make me wait! or Building High-Performance Web Applications
Don't make me wait! or Building High-Performance Web Applications
 
HTML 5 & CSS 3
HTML 5 & CSS 3HTML 5 & CSS 3
HTML 5 & CSS 3
 
jQuery UI and Plugins
jQuery UI and PluginsjQuery UI and Plugins
jQuery UI and Plugins
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
 
HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs Silverlight
 
Mobile HTML, CSS, and JavaScript
Mobile HTML, CSS, and JavaScriptMobile HTML, CSS, and JavaScript
Mobile HTML, CSS, and JavaScript
 
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation
 
Building an HTML5 Video Player
Building an HTML5 Video PlayerBuilding an HTML5 Video Player
Building an HTML5 Video Player
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
 

Andere mochten auch

Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slidesSmithss25
 
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Shreeraj Shah
 
Refreshing Your UI with HTML5, Bootstrap and CSS3
Refreshing Your UI with HTML5, Bootstrap and CSS3Refreshing Your UI with HTML5, Bootstrap and CSS3
Refreshing Your UI with HTML5, Bootstrap and CSS3Matt Raible
 
El viaje al poder de la conciencia
El viaje al poder de la concienciaEl viaje al poder de la conciencia
El viaje al poder de la concienciaEuler
 
Delta c200 catalog
Delta c200 catalogDelta c200 catalog
Delta c200 catalogElectromate
 
Planificación educativa de talleres
Planificación educativa de talleres Planificación educativa de talleres
Planificación educativa de talleres José Luis Machaca
 
Estruturas organizacionales
Estruturas organizacionalesEstruturas organizacionales
Estruturas organizacionalesforeguer
 
Acta de compromiso paem sena ie
Acta de compromiso paem sena ieActa de compromiso paem sena ie
Acta de compromiso paem sena iearticulacionatl
 
Manual+de+camtasia+para+bibliotecarios
Manual+de+camtasia+para+bibliotecariosManual+de+camtasia+para+bibliotecarios
Manual+de+camtasia+para+bibliotecariosadrianchy
 
Fundamentos del Arte Tema 4 Antigüedad (III) Roma
Fundamentos del Arte Tema 4 Antigüedad (III) Roma Fundamentos del Arte Tema 4 Antigüedad (III) Roma
Fundamentos del Arte Tema 4 Antigüedad (III) Roma ANA GALVAN ROMARATE-ZABALA
 
Visa boas práticas de distribuição, armazenamento e transporte de medicamentos
Visa   boas práticas de distribuição, armazenamento e transporte de medicamentosVisa   boas práticas de distribuição, armazenamento e transporte de medicamentos
Visa boas práticas de distribuição, armazenamento e transporte de medicamentosHEBERT ANDRADE RIBEIRO FILHO
 
El viaje al poder de la conciencia
El viaje al poder de la concienciaEl viaje al poder de la conciencia
El viaje al poder de la concienciaEuler
 
Ifsp tramiteprocedimientosciviles
Ifsp tramiteprocedimientoscivilesIfsp tramiteprocedimientosciviles
Ifsp tramiteprocedimientoscivilesGina's Jewelry
 

Andere mochten auch (20)

Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
AJAX and JSON
AJAX and JSONAJAX and JSON
AJAX and JSON
 
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
 
Refreshing Your UI with HTML5, Bootstrap and CSS3
Refreshing Your UI with HTML5, Bootstrap and CSS3Refreshing Your UI with HTML5, Bootstrap and CSS3
Refreshing Your UI with HTML5, Bootstrap and CSS3
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
El viaje al poder de la conciencia
El viaje al poder de la concienciaEl viaje al poder de la conciencia
El viaje al poder de la conciencia
 
Delta c200 catalog
Delta c200 catalogDelta c200 catalog
Delta c200 catalog
 
Planificación educativa de talleres
Planificación educativa de talleres Planificación educativa de talleres
Planificación educativa de talleres
 
Visor general de fallasmayo13
Visor general de fallasmayo13Visor general de fallasmayo13
Visor general de fallasmayo13
 
Modelos de comunicacion
Modelos de comunicacionModelos de comunicacion
Modelos de comunicacion
 
Sofia final 7 (1)
Sofia final 7 (1)Sofia final 7 (1)
Sofia final 7 (1)
 
Estruturas organizacionales
Estruturas organizacionalesEstruturas organizacionales
Estruturas organizacionales
 
Pila osi
Pila osiPila osi
Pila osi
 
Acta de compromiso paem sena ie
Acta de compromiso paem sena ieActa de compromiso paem sena ie
Acta de compromiso paem sena ie
 
Manual+de+camtasia+para+bibliotecarios
Manual+de+camtasia+para+bibliotecariosManual+de+camtasia+para+bibliotecarios
Manual+de+camtasia+para+bibliotecarios
 
Fundamentos del Arte Tema 4 Antigüedad (III) Roma
Fundamentos del Arte Tema 4 Antigüedad (III) Roma Fundamentos del Arte Tema 4 Antigüedad (III) Roma
Fundamentos del Arte Tema 4 Antigüedad (III) Roma
 
Teoria Del Color
Teoria Del ColorTeoria Del Color
Teoria Del Color
 
Visa boas práticas de distribuição, armazenamento e transporte de medicamentos
Visa   boas práticas de distribuição, armazenamento e transporte de medicamentosVisa   boas práticas de distribuição, armazenamento e transporte de medicamentos
Visa boas práticas de distribuição, armazenamento e transporte de medicamentos
 
El viaje al poder de la conciencia
El viaje al poder de la concienciaEl viaje al poder de la conciencia
El viaje al poder de la conciencia
 
Ifsp tramiteprocedimientosciviles
Ifsp tramiteprocedimientoscivilesIfsp tramiteprocedimientosciviles
Ifsp tramiteprocedimientosciviles
 

Ähnlich wie How to make Ajax work for you

Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajaxs_pradeep
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.Nerd Tzanetopoulos
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applicationsdominion
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...BradNeuberg
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
Pascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax SecurityPascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax Securityamiable_indian
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Implementing Ajax In ColdFusion 7
Implementing Ajax In ColdFusion 7Implementing Ajax In ColdFusion 7
Implementing Ajax In ColdFusion 7Pranav Prakash
 

Ähnlich wie How to make Ajax work for you (20)

Ajax
AjaxAjax
Ajax
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Pascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax SecurityPascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax Security
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
 
Ajax3
Ajax3Ajax3
Ajax3
 
Ajax Lecture Notes
Ajax Lecture NotesAjax Lecture Notes
Ajax Lecture Notes
 
Ajax
AjaxAjax
Ajax
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Implementing Ajax In ColdFusion 7
Implementing Ajax In ColdFusion 7Implementing Ajax In ColdFusion 7
Implementing Ajax In ColdFusion 7
 

Mehr von Simon Willison

Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startupsSimon Willison
 
The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)Simon Willison
 
How we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphHow we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphSimon Willison
 
Web Services for Fun and Profit
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and ProfitSimon Willison
 
Tricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationTricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationSimon Willison
 
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricAdvanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricSimon Willison
 
How Lanyrd uses Twitter
How Lanyrd uses TwitterHow Lanyrd uses Twitter
How Lanyrd uses TwitterSimon Willison
 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approvalSimon Willison
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesSimon Willison
 
Building crowdsourcing applications
Building crowdsourcing applicationsBuilding crowdsourcing applications
Building crowdsourcing applicationsSimon Willison
 
Evented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesEvented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesSimon Willison
 
Cowboy development with Django
Cowboy development with DjangoCowboy development with Django
Cowboy development with DjangoSimon Willison
 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with DjangoSimon Willison
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
Web App Security Horror Stories
Web App Security Horror StoriesWeb App Security Horror Stories
Web App Security Horror StoriesSimon Willison
 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror StoriesSimon Willison
 

Mehr von Simon Willison (20)

How Lanyrd does Geo
How Lanyrd does GeoHow Lanyrd does Geo
How Lanyrd does Geo
 
Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startups
 
The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)
 
Building Lanyrd
Building LanyrdBuilding Lanyrd
Building Lanyrd
 
How we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphHow we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graph
 
Web Services for Fun and Profit
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and Profit
 
Tricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationTricks & challenges developing a large Django application
Tricks & challenges developing a large Django application
 
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricAdvanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
 
How Lanyrd uses Twitter
How Lanyrd uses TwitterHow Lanyrd uses Twitter
How Lanyrd uses Twitter
 
ScaleFail
ScaleFailScaleFail
ScaleFail
 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
 
Building crowdsourcing applications
Building crowdsourcing applicationsBuilding crowdsourcing applications
Building crowdsourcing applications
 
Evented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesEvented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunnies
 
Cowboy development with Django
Cowboy development with DjangoCowboy development with Django
Cowboy development with Django
 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with Django
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
Web App Security Horror Stories
Web App Security Horror StoriesWeb App Security Horror Stories
Web App Security Horror Stories
 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror Stories
 

Kürzlich hochgeladen

UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 

Kürzlich hochgeladen (20)

UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 

How to make Ajax work for you

  • 1. How to make work for you Simon Willison - http://simonwillison.net/ Web 2.0 Expo Berlin 5th November 2007
  • 2. In this talk • Where Ajax came from • When you should (and shouldn’t) use it • Ajax fundamentals (including a DOM and JavaScript refresher) • Advanced Ajax techniques • Picking and using a JavaScript library
  • 5. AJAX v.s. Ajax “Asynchronous JavaScript + XML”
  • 6. AJAX v.s. Ajax “Any technique that “Asynchronous allows the client to JavaScript + XML” retrieve more data from the server without reloading the whole page”
  • 7. Why did Ajax happen? • Two reasons: • The browsers that mattered all added support for IE’s XMLHttpRequest object (which IE has had since 1998) • Jesse James Garrett came up with a name that sucked a lot less than “XMLHttpRequest” did
  • 8. Pre-Ajax... • “Remote Scripting” (not as catchy) • Various unpleasant but ingenious hacks: • Scriptable Java applets • Passing data through changes to a cookie • Passing data through a hidden iframe • (That one’s actually still in use)
  • 20. Some anti-patterns • Drag and drop shopping carts • Massive page updates e.g. pagination • Unlinkable content (see also bookmarking) • Breaking browser expectations • Forgetting the loading icon!
  • 22. The three legged stool (X)HTML CSS JavaScript
  • 23. The three legged stool The DOM (X)HTML CSS JavaScript
  • 26. The DOM <html> <head> <body> <title> <div id=quot;headquot;> <div id=quot;mainquot;> <h1> <p> <p> <p>
  • 27. Key DOM methods • document.getElementsByTagName, document.getElementById • el.childNodes, el.parentNode, el.firstChild, el.nextSibling, el.getAttribute • el.appendChild, el.insertBefore, el.setAttribute, el.removeChild • document.createElement, document.createTextNode http://www.howtocreate.co.uk/tutorials/javascript/domstructure
  • 28. JavaScript doesn’t suck! • Just remember; your; semicolons; • Avoid accidental globals: always declare your variables with “var” • Take the time to figure out higher order programming, where you treat functions as objects
  • 29. CSS class switching • Often if you are dynamically making large- scale changes to the layout of a page... • ... you can do most of the work by defining an alternative CSS class ... • ... and then switching a container element’s className property in your JavaScript
  • 31. Firebug • Inspect HTML elements to see what CSS rules currently apply to them • Interactive console for experimenting with JavaScript against the loaded page • Full JavaScript debugger, including breakpoints • Profile your code and your site’s assets and Ajax requests • Logging with console.log() and friends
  • 32. XMLHttpRequest • The object that lets you make HTTP requests from within JavaScript • IE had it first, using an ActiveX Object • Almost nothing to do with XML • Asynchronous (so you use callbacks)
  • 33. XMLHttpRequest • The object that lets you make HTTP requests from within JavaScript • IE had it first, using an ActiveX Object • Almost nothing to do with XML • Asynchronous (so you use callbacks)
  • 34. var xhr = createXHR(); xhr.onreadystatechange = onComplete; xhr.open('GET', '/helloworld.txt', true); xhr.send(null); function onComplete() { if (xhr.readyState == 4) { if (xhr.status == 200) { alert(xhr.responseText); } else { alert('Error code ' + xhr.status); } } }
  • 35. var xhr = createXHR(); xhr.onreadystatechange = onComplete; xhr.open('GET', '/helloworld.txt', true); xhr.send(null); function onComplete() { if (xhr.readyState == 4) { if (xhr.status == 200) { alert(xhr.responseText); } else { alert('Error code ' + xhr.status); } } }
  • 36. var xhr = createXHR(); xhr.onreadystatechange = onComplete; xhr.open('GET', '/helloworld.txt', true); xhr.send(null); function onComplete() { if (xhr.readyState == 4) { if (xhr.status == 200) { alert(xhr.responseText); } else { alert('Error code ' + xhr.status); } } }
  • 37. var xhr = createXHR(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { alert(xhr.responseText); } else { alert('Error code ' + xhr.status); } } }; xhr.open('GET', '/helloworld.txt', true); xhr.send(null);
  • 38. function createXHR() { var xhr = null; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} } return xhr; }
  • 39. function createXHR() { var xhr = null; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} } return xhr; }
  • 40. var xhr = createXHR(); xhr.onreadystatechange = onComplete; xhr.open('POST', '/helloworld.php', true); xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' ); xhr.send('name=Simon&age=26');
  • 41. xhr.open('POST', '/helloworld.php', true); The third argument specifies that we want to make an asynchronous request (“tell me when you’re done by calling this function”). If you set this to false you’ll get a synchronous request, which will completely hang the browser until the request returns. Don’t do that.
  • 42. Too much boilerplate? • That’s quite a lot to remember • Best option: don’t remember any of it! • Use a good library instead • Lots more on those later on
  • 43. doRequest doRequest(quot;GETquot;, quot;/blah.txtquot;, null, function(xhr) { doSomethingWith(xhr.responseText); }); doRequest(quot;GETquot;, quot;/getinfo.phpquot;, { quot;namequot;: quot;Simonquot; }, function(xhr) { doSomethingWith(xhr.responseText); }); doRequest(quot;POSTquot;, quot;/getinfo.phpquot;, { quot;namequot;: quot;Simonquot; }, function(xhr) { doSomethingWith(xhr.responseText); });
  • 44. function doRequest(method, url, args, callback) { var xhr = createXHR(); method = method.toUpperCase(); args = args && buildQueryString(args); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { callback(xhr); } }; if (method == 'GET' && args) { url += '?' + args; args = null; } xhr.open(method, url, true); if (method == 'POST') { xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' ); } xhr.send(args); }
  • 45. function buildQueryString(obj) { var bits = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { bits[bits.length] = escape(key) + '=' + escape(obj[key]); } } return bits.join('&'); } var s = buildQueryString({ name: 'Simon', age: 26 }); name=Simon&age=26
  • 47. Client data submission • Requests can have anything you like in the body: • HTML, XML, JSON... • So if you really want to, you can access SOAP or XML-RPC services from JavaScript • For almost all purposes, regular form arguments suffice • REST APIs are a good fit as well
  • 48. Server responses • Plain text • HTML fragments • CSV or similar • XML • Executable JavaScript • JSON
  • 49. Plain text • Just sending back a simple value • xhr.responseText is all you need • Pros: • Absurdly simple • Cons: • Only supports a single value or string
  • 50. HTML fragments • Return an HTML fragment, and inject it using innerHTML function onSuccess(xhr) { var div = document.getElementById('response'); div.innerHTML = xhr.responseText; } <div id=quot;responsequot;> </div>
  • 51. Fragment pros and cons • Pros: • Again, really simple • You can leverage existing server-side templates and techniques • Cons: • You have to change your server-side code to change client-side behaviour • You can't reuse your endpoint
  • 52. Executable JavaScript • We can pass JavaScript code back from the server and execute it directly document.getElementById( 'response').innerHTML = 'Done!'; function onSuccess(o) { eval(o.responseText); }
  • 53. Pros: • Incredibly simple client-side code • The server can do abolutely anything, without needing to modify the client-side code • Cons: • Weird factoring of code - dynamically generating code to run on the client makes it hard to keep track of the big picture • How about just sending structured data?
  • 54. CSV or similar • We want structured data! Simon Willison,26,simon@simonwillison.net • Pros: • Easy to parse: xhr.responseText.split(','); • Cons: • How do we pass values containing commas? • Index based, so brittle and hard to maintain
  • 55. XML • Surely XML will save us! <person> <name>Simon</name> <age>26</age> </person> function onSuccess(xhr) { var dom = xhr.responseXML; showPerson( dom.getElementsByTagName('name')[0].data, parseInt(dom.getElementsByTagName('age')[0].data, 10) }); }
  • 56. XML pros and cons • Pros: • We can re-use our DOM knowledge • xhr.responseXML parses it for us • We can call existing Web Services directly • Cons: • Verbose handling code • Is this the simplest thing that could possibly work?
  • 57. JSON • A standard for representing common data structures, quot;discoveredquot; by Douglas Crockford • Common data structures? • Associative arrays (dictionaries / hashes) • Arrays (lists) • Numbers, strings, booleans • A subset of JavaScript syntax
  • 58. JSON example {quot;namequot;: quot;Simonquot;, quot;agequot;: 26} function onSuccess(xhr) { var person = eval('(' + xhr.responseText + ')') ... )
  • 59. More complex JSON {quot;peoplequot;: [{ quot;namequot;: quot;Simonquot;, quot;emailquot;: quot;simon@simonwillison.netquot; }, { quot;namequot;: quot;Nataliequot;, quot;emailquot;: quot;nat@natbat.netquot; } ]} function onSuccess(xhr) { var people = eval('(' + xhr.responseText + ')'); ... }
  • 60. To compare... <people> <person> <name>Simon</name> <email>simon@simonwillison.net</email> </person> <person> <name>Natalie</name> <email>nat@natbat.net</email> </person> </people>
  • 61. To compare... function onSuccess(o) { var dom = o.responseXML; var people = []; var people_els = dom.getElementsByTagName('people'); for (var i = 0, el; el = people_els[i]; i++) { people[people.length] = { 'name': el.getElementsByTagName('name')[0].data, 'email': el.getElementsByTagName('email')[0].data }; } ... }
  • 62. JSON v.s. XML JSON XML Bytes (excluding whitespace) 95 156 Lines of code to process 1 7+
  • 63. It ain’t just for JavaScript • Libraries for consuming and generating JSON are available for many languages, including: • Python • Ruby • PHP • Java ... • JSON works really well as a general purpose tool for exchanging data structures
  • 64. Aside: XSLT • Modern browsers support XSLT transforms - albeit with differing APIs • These can be significantly faster than regular DOM manipulation • If you're having performance problems, this may be worth looking in to
  • 65. Recommendations • For quick and simple apps, HTML fragments offer the path of least resistance • For most purposes, JSON makes the most sense • Use XML if you already have an XML Web Service that you want to consume (or you need an XSLT speed boost)
  • 66. Let’s see some running code
  • 69. The same-origin restriction • XMLHttpRequest is only allowed to communicate with the domain from which the page was loaded • The same is true of JavaScript calls between windows, frames and iframes • This is a critical browser security feature
  • 70. The intranet attack • http://wiki.private.corp/ contains private data • User is tricked in to visiting evilexample.com • evilexample.com uses XMLHttpRequest (or a hidden iframe child) to load and steal data from http://wiki.private.corp/
  • 71. • JSON-P offers a (hackish) solution to the cross-domain XMLHttpRequest restriction http://example.com/query?name=Simon callback({quot;namequot;: quot;Simonquot;, quot;agequot;: 26}); function loadJSON(url) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; document.getElementsByTagName('head')[0].appendChild(script); } function callback(person) { ... } loadJSON('http://example.com/query?name=' + name);
  • 72. • JSON-P offers a (hackish) solution to the cross-domain XMLHttpRequest restriction http://example.com/query?name=Simon callback({quot;namequot;: quot;Simonquot;, quot;agequot;: 26}); function loadJSON(url) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; document.getElementsByTagName('head')[0].appendChild(script); } function callback(person) { ... } loadJSON('http://example.com/query?name=' + name);
  • 73. Pros and cons • Pros: • Lets you call services hosted on other domains, provided they opt-in • del.icio.us, Flickr, other sites offer this • Cons: • Detecting errors is harder than with XMLHttpRequest • You have to trust the site who’s code you are executing
  • 74. XSS
  • 75. • XSS attacks occur when a malicious third party injects untrusted code (HTML, CSS or JavaScript) in to your page • It’s generally a server-side consideration, but you need to take it in to consideration when writing JavaScript as well • Ajax can compound the problem by allowing users to create self-propagating “worms”
  • 76. CSRF
  • 77. CSRF for GET <img src=quot;http://example.com/admin/delete.php?id=5quot;> Trick someone who is signed in to example.com/admin/ in to visiting a page hosting that image and you’ll force them to delete something.
  • 78. CSRF for POST <form id=quot;evilquot; action=quot;http://example.com/admin/delete.phpquot; method=quot;POSTquot;> <input type=quot;hiddenquot; name=quot;idquot; value=quot;5quot;> </form> <script> document.getElementById('evil').submit() </script>
  • 79. CSRF protection • For regular forms, add a hidden field with a one-time secret token and check for that token on every submission • For Ajax, either do the above or use: xhr.setRequestHeader( quot;X-Requested-Withquot;, quot;XMLHttpRequestquot; );
  • 81. Unobtrusive JavaScript • JavaScript isn't always available • Security conscious organisations (and users) sometimes disable it • Some devices may not support it (mobile phones for example) • Assistive technologies (screen readers) may not play well with it • Search engine crawlers won't execute it • Unobtrusive: stuff still works without it!
  • 82. Progressive enhancement • Start with solid markup • Use CSS to make it look good • Use JavaScript to enhance the usability of the page • The content remains accessible no matter what
  • 83. Adding events • Unobtrusive JavaScript relies on adding event handlers after the fact • The naive way of doing this: window.onload = function() { for (var i = 0, link; link = document.links[i]; i++) { if (link.className == 'external') { link.onclick = function() { window.open(this.href); return false; } } } };
  • 84. Problem • If you later assign something else to window.onload (or one of the link.onclicks) you will clobber your behaviour • You should add events quot;properlyquot;... • Different in different browsers • attachEvent v.s. addEventListener • My advice: use a library!
  • 86. labels.js • One of the earliest examples of this technique, created by Aaron Boodman (now of Greasemonkey and Google Gears fame)
  • 89. How it works <label for=quot;searchquot;>Search</label> <input type=quot;textquot; id=quot;searchquot; name=quot;qquot;> • Once the page has loaded, the JavaScript: • Finds any label elements linked to a text field • Moves their text in to the associated text field • Removes them from the DOM • Sets up the event handlers to remove the descriptive text when the field is focused • Clean, simple, reusable
  • 90. easytoggle.js • An unobtrusive technique for revealing panels when links are clicked <ul> <li><a href=quot;#panel1quot; class=quot;togglequot;>Panel 1</a></li> <li><a href=quot;#panel2quot; class=quot;togglequot;>Panel 2</a></li> <li><a href=quot;#panel3quot; class=quot;togglequot;>Panel 3</a></li> </ul> <div id=quot;panel1quot;>...</div> <div id=quot;panel2quot;>...</div> <div id=quot;panel3quot;>...</div>
  • 93. How it works • When the page has loaded... • Find all links with class=quot;togglequot; that reference an internal anchor • Collect the elements that are referenced by those anchors • Hide all but the first • Set up event handlers to reveal different panels when a link is clicked • Without JavaScript, links still jump to the right point
  • 94. Django filter lists • Large multi-select boxes aren't much fun • Painful to scroll through • Easy to lose track of what you have selected • Django's admin interface uses unobtrusive JavaScript to improve the usability here
  • 97. • Ajax is often used to avoid page refreshes • So... • Write an app that uses full page refreshes • Use unobtrusive JS to quot;hijackquot; links and form buttons and use Ajax instead • Jeremy Keith coined the term quot;Hijaxquot; to describe this
  • 98. More progressive Ajax suggestions • Live search / filtering • Adding comments / tags • Smart form validation • Checking if usernames are already taken • You could even make a progressively enhanced chat room
  • 99. The onload problem • All of these examples use code that runs when the window quot;loadquot; event is fired • Wait until page is loaded, then manipulate the DOM • Problem: If the page takes a while to load (large inline images) there will be a Flash Of Unstyled Content (FOUC) • Also, if the user clicks things before the setup code has fired they won't get the expected behaviour.
  • 100. document.write(css) • If the effect requires hiding some otherwise visible elements, you can document.write a stylesheet <script type=quot;text/javascriptquot;> document.write('<style type=quot;text/cssquot;>'; document.write('.hideme { display: none }'); document.write('</style>'); </script>
  • 101. body.onclick • If your effect is triggered by the user clicking on something, attach code to the document.body quot;clickquot; event right at the start of your code (no need to wait for the document quot;loadquot; event) YAHOO.util.Event.on(document.body, 'click' function(e) { var clicked_el = YAHOO.util.Event.getTarget(e); // ... }
  • 102. onDOMReady • A number of attempts have been made to create an onDOMReady event that fires when the DOM has been constructed but before the page has loaded • dean.edwards.name/weblog/2006/06/again/ • Modern libraries all support this in some form • Problem: CSS may not have loaded, so calculated dimensions may be incorrect
  • 103. • Unobtrusive JavaScript is the Right Way to go about things, but runs in to browser differences even faster than regular JavaScript • Which leads us neatly on to...
  • 104. Frameworks and Libraries
  • 105. JavaScript libraries • ajaxpatterns.org lists over 40 general purpose JavaScript libraries • ... and that’s not including the many libraries tied to a specific server-side language • Why are there so many of them?
  • 106. “The bad news: JavaScript is broken. The good news: It can be fixed with more JavaScript!” Geek folk saying
  • 107. Inconsistent event model (thanks, IE) • Positioning and co-ordinates • Memory management (thanks, IE) • The DOM is a horrible API! • JavaScript-the-language has quite a few warts • But it’s powerful enough to let you fix them • Classes and inheritance can be confusing • Many useful JS utility functions are missing • Drag and drop and Animation are really hard
  • 108. Narrowing them down... • Prototype (and Scriptaculous) • The Yahoo! User Interface Library - YUI • jQuery • The Dojo Toolkit
  • 109. Honourable mentions • MochiKit • No updates since early 2006 • The Google Web Toolkit • I don’t do Java • mooTools • Lots of buzz, but I haven’t figured out why yet
  • 110. Download Get the latest version—1.5.1 Learn Prototype is a JavaScript Framework that aims to Online documentation and resources. ease development of dynamic web applications. Discuss Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype Mailing list and IRC is quickly becoming the codebase of choice for web application developers everywhere. Contribute Submit patches and report bugs. Prototype and Scriptaculous Prototype and script.aculo.us: The quot;Bungee bookquot; has landed! Who's using Prototype? Meet the developers Core team member Christophe Porteneuve has been hard at work for the past few months tracking
  • 111. • Prototype focuses on basic browser compatibility and JavaScript language enhancement • Tries to make JavaScript more like Ruby • Extends most of JavaScript’s built-in objects with new functionality • Scriptaculous adds fancy effects, basic widgets and drag and drop
  • 112. $$('#bmarks li').each(function(li){ Event.observe(li, 'click', function(e) { this.style.backgroundColor = 'yellow'; }.bindAsEventListener(li)); });
  • 113. The Yahoo UI Library
  • 114. • Created at Yahoo!, BSD licensed • Designed for both creating new applications and integration with legacy code • Focused on browser issues; almost no functionality relating to JS language itself • Extensively tested and documented
  • 115. controls calendar container autocomplete menu slider treeview dragdrop animation dom event connection utilities
  • 116. YAHOO.util.Event.on(window, 'load', function() { var div = YAHOO.util.Dom.get('messages'); setTimeout(function() { var anim = new YAHOO.util.Anim(div, { height: {to: 0}, opacity: {to: 0} }, 0.4); anim.animate(); anim.onComplete.subscribe(function() { div.parentNode.removeChild(div); }); }, 2000); });
  • 117. Common YUI idiom $E = YAHOO.util.Event; $D = YAHOO.util.Dom; $E.on(window, 'load', function() { var div = $D.get('messages'); ... });
  • 118. jQuery
  • 119. jQuery(function($) { $(quot;a.hidemequot;). css('color', 'red'). click(function() { $(this).hide(quot;slowquot;); return false; }); });
  • 120. Simple philosophy: find some nodes, then do something to them • Minimal impact on your global namespace - it adds two global symbols: jQuery and $, and $ can be easily reverted • API designed around “chaining” - other libraries are now emulating this • Outstanding node selection, based on CSS 3 and custom extensions • Small core library with an intelligent plugin mechanism
  • 121. Dojo
  • 122. • The oldest of the current popular libraries, pre-dating even Ajax • Incredible amounts of functionality • Used to suffer from a tough learning curve, although the 0.9 release simplifies things greatly
  • 123. Dojo components • dojo • Core library, similar to jQuery etc • Smart package managment with dynamic code loading • dijit • Advanced widget system • dojox • Dojo eXperimental - crazy voodoo magic
  • 124. dijit
  • 126. div dojoType=quot;dijit.layout.TabContainerquot; sizeShare=quot;40quot; div id=quot;tab1quot; dojoType=quot;dijit.layout.ContentPanequot; title=quot;Form Feelquot; h2Various Form Elements:/h2 form name=quot;dijitFormTestquot; pinput type=quot;checkBoxquot; dojoType=quot;dijit.form.CheckBoxquot; checked=quot;checkedquot; Standard Dijit CheckBox brinput type=quot;checkBoxquot; dojoType=quot;dijit.form.CheckBoxquot; disabled=quot;disabledquot; Disabled Dijit br input type=quot;checkBoxquot; dojoType=quot;dijit.form.CheckBoxquot; disabled=quot;disabledquot; checked=quot;checkedquot; Checked and Disabled Dijit /p ...
  • 127. dojox
  • 128. • Graphics (cross-browser drawing API) • Offline storage • Cryptography • Templating • Data grids and more • “The future of the browser today”
  • 130. My library selection criteria • Enables unobtrusive JavaScript • Plays well with other code • Smart use of namespacing • Global variable impact kept to a minimum • Tie breaker: the less code I have to write the better!
  • 131. • I’m currently using and recommending jQuery for most situations • But... there’s cut-throat competition between the various libraries at the moment • This is one of the reasons I care about interoperability - commit to a single library and you might lose out when one of the others jumps ahead of it
  • 132. The law of leaky abstractions
  • 133. http://www.joelonsoftware.com/articles/LeakyAbstractions.html My interpretation: The more you rely on abstractions, the worse off you’ll be when one of them leaks