Simple Twitter App with jQuery Templates and JSONP

August 24th, 2009 admin Comments off

I’ve been trying to come up with some cool applications for the jQuery Templates Plugin. So Twitter hosts this cool jsonp interface that enables you to pull down all kinds of twitter data to your client application – jsonp enables us to get around XSS, so the application doesn’t need a server-side component at all!!!

Check out the code:

<form id="twitter_search" >
   <label for="twitter_search" >Search Twitter Feed:</label>
   <input type="text" name="q" value="GUICenter" />
   <input type="submit" name="submit" value="Submit" />
 </form>
 <div id="twitter_results_tmpl" style="display:none" >
   <h4>Tweets from {name}</h4>
     <ul>
       <li style="display:none" >{text} <br/ >Created At: {created_at}</li>
    </ul>
 </div>

Twitter = {

			init: function()
			{
				$('#twitter_search').submit(Twitter.search);
			},

			search: function()
			{
				$.ajax({
					'url': 'http://twitter.com/statuses/user_timeline/'+$(this.q).val()+'.json',
					'data': { count: 5 },
					'success': Twitter.onSearchResult,
					'dataType': 'jsonp'
				});

				return false;

			},

			onSearchResult: function(res)
			{
				$('#twitter_results_tmpl')
					.render(res[0]['user'],{clone:true})
					.removeAttr('id')
					.find('.twitter_tmpl')
					.render( res, {clone:true} )
				  .show().end().end().show();
			}

		};

		$(document).ready( Twitter.init );

Try it out…


Cool, eh? ;)

Categories: jQuery Tags:

jQuery Templates-1.0.0 released!

August 20th, 2009 admin Comments off

Just released a new jQuery plugin!

Here is the excerpt:

The jQuery templates plugin enables you to use jQuery and HTML as a template engine. Why would you want to use JavaScript as a template engine you might ask? One of the primary reasons is to perform easy token replacements inside the DOM when you receive data back from an AJAX call. Typically (especially when using frameworks like jQuery) you won’t want to put your html inside a JS file, but rather use the code to manipulate the html already inside the DOM. The jQuery templates function allows you to apply template token replacements to any section of markup in the DOM, and even clone templates when you have an array of new values.

On plugins.jquery.com: http://plugins.jquery.com/project/Templates

Full Documentation Here

Categories: jQuery Tags:

jQuery outerHtml()

August 18th, 2009 admin Comments off

Today I’ve been working on some template stuff using jquery and I realized I need a way to get the entire html string for a particular selector, not just the innerHtml contents. Hmm, that sounds like something called outerHtml…

Okay, better google for outerHtml: yes… no… grrrrr… there is an outerHtml property, but only for IE. So lets see if we can roll our own cross-browser solution using jquery:

jQuery.fn.extend( {

  outerHtml: function( replacement )
  {
    // We just want to replace the entire node and contents with
    // some new html value
    if (replacement)
    {
      return this.each(function (){ $(this).replaceWith(replacement); });
    }

    /*
     * Now, clone the node, we want a duplicate so we don't remove
     * the contents from the DOM. Then append the cloned node to
     * an anonymous div.
     * Once you have the anonymous div, you can get the innerHtml,
     * which includes the original tag.
     */
    var tmp_node = $("<div></div>").append( $(this).clone() );
    var markup = tmp_node.html();

    // Don't forget to clean up or we will leak memory.
    tmp_node.remove();
    return markup;
  }
});

So that basically gets us an outerHtml() function! The method also lets you do outerHtml replacements, which is basically just a wrapper around replaceWith(). Pretty fun!

So now, how do we use it?

<div class="outer" >Fun Stuff</div>

// get the entire html for the <div class="outer" > tag
var x = $('.outer').outerHtml();

// replace all div tags with <div class="outer" >Fun Stuff</div>
$('div').outerHtml(x);
Categories: jQuery Tags:

Efficient jQuery Selectors

March 23rd, 2009 admin Comments off

jQuery is seriously awesome, but if we don’t use it carefully we can put a pretty serious load on the users’ CPU.  This can mean a perceptible delay when the $(document).ready() function runs if there are loads of un-optimized selectors running. Considering that most users spend 4 seconds on a site, 1 or 2 seconds of delay can mean losing your user.  What kinds of jQuery selectors are fastest? Which ones are slower, and which ones must we avoid at all costs to ensure a responsive experience?

Which is fastest?

$(’.box_text’).html(’test1′);
$(’span.box_text’).html(’test2′);
$(’#box_text’).html(’test3′);

Which is fastest? Have a look for yourself on this test page, http://www.ivorycity.com/tests/jquery/selectors/test0.php.

If you’re using FF3, they should all be about the same, but if you’re using IE6,7, or FF2, $(’#box_text’) is up to 10x faster than $(’.box_text’)!

Why is this?

In order to answer these questions, we need to know a little about how jQuery finds DOM nodes.

Internally, jQuery uses document.getElementById() to find elements based on id. Browsers index id’s internally, so the lookup is instantaneous.  Meanwhile,  using $(’.someclass’) in IE causes jQuery to iterate over every element in the DOM to find one with a particular class – that’s crazy slow!

By prefixing ’span’ to the query, we get $(’span.box_text’) – this is a little better because internally, jQuery calls document.getElementsByTagName and iterates the results. Since spans are only a sub-set of all DOM nodes, the query is a lot faster. So if you’re performing lots of ‘naked’ class selectors, you’re going to consume a lot of user cpu.

In Firefox 3 however,  it’s no longer the case that $(’.someclass’) causes an iteration over the DOM; document.getElementsByClassName() was added in FF3 to index element class names inside the browser memory space, which is much, much faster. That’s why we don’t see the same performance hit as in IE.

Now, it may not always be appropriate to access elements by id. If you’re trying to find many instances, say 100+, with a particular class name, it’s actually faster to use $(’.someclass’) than to loop through a set of id’s.

The moral of the story…

1) Use id selectors to reference a ‘needle in a haystack’

2) Use class selectors prudently, and only when referencing large numbers of DOM nodes

3) You can also prevent iteration over the entire dom by doing something like $(’#myid .myclass’) which only searches sub-nodes of #myid.

Categories: jQuery Tags: ,