<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Scriptble &#187; jQuery</title>
	<atom:link href="http://scriptble.com/tag/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://scriptble.com</link>
	<description>{ js : performance }</description>
	<lastBuildDate>Wed, 01 Feb 2012 20:02:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Getting A Class From a DOM Element</title>
		<link>http://scriptble.com/2011/05/getting-a-class-from-a-dom-element/</link>
		<comments>http://scriptble.com/2011/05/getting-a-class-from-a-dom-element/#comments</comments>
		<pubDate>Fri, 13 May 2011 19:34:32 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[Do This, Not That]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM Manipulation]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=200</guid>
		<description><![CDATA[Lately, if I am searching for a way to do something in Javascript the only results I am getting ways of doing the procedure using jQuery. While, its true jQuery is pretty much the de facto standard for writing JavaScript anymore, understanding the underlying technology is a must. As well as alot of times, I [...]]]></description>
			<content:encoded><![CDATA[<p>Lately, if I am searching for a way to do something in Javascript the only results I am getting ways of doing the procedure using jQuery. While, its true jQuery is pretty much the de facto standard for writing JavaScript anymore, understanding the underlying technology is a must. As well as alot of times, I don't need to load jQuery on the page just to get a DOM Element or its class.</p>

<p>So I recently went looking on how to <a href="http://tinyurl.com/3w5m6t5">get class from element</a> in JavaScript. Turns out most of the results were for getting elements by class name, rather than actually getting the class of the element I already had.</p>

<p>Here is how you get a class name from an Element using JavaScript.</p>
<span id="more-200"></span>
<pre class="language-javascript">
	document.getElementById("tag_cloud-2").className
</pre>
<br/>
<pre>
	Output:
		"sidebaritem widget_tag_cloud"
</pre>
<br/>
<p>Now, that wasn't so hard.  Lets take a look at a performance test: <a href="http://jsperf.com/jquery-versus-classname">jQuery versus getting a className</a>.</p>

<p>Here is the setup for the test</p>
<pre>
&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"&gt;&lt;/script&gt;

&lt;div class="wrapper"&gt;
	&lt;div class="innerWrapper"&gt;
		&lt;div id="getMe" class="button"&gt;
			&lt;a href="javascript:void(0)" id="button" class="buttonRef"&gt;
				&lt;span class="buttonText"&gt;Text&lt;/span&gt;
			&lt;/a&gt;
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
	var jElem = $("#getMe");
	var dElem = document.getElementById("getMe");
&lt;/script&gt;
</pre>
<br/>
<p>Here are the tests:</p>
<pre>
1. jQuery - get Element + get Class   $("#getMe").attr('class');
2. GET DOM ELEM + get Class           document.getElementById("getMe").className;
3. jQuery get Class                   jElem.attr('class');
4. DOM get class                      dElem.className;
</pre>

<h2>Chrome 11 Results</h2>
<p>
In Chrome using a cached element, getting the classname is 48x faster than using jQuery.<br/>
In Chrome getting the element and then getting the classname is 25x faster than using jQuery.<br/>
</p>

<h2>FF 4.0 Results</h2>
<p>
In FF using a cached element, getting the classname is 65x faster than using jQuery.<br/>
In FF getting the element and then getting the classname is 83x faster than using jQuery.<br/>
</p>

<h2>Safari 5.0 Results</h2>
<p>
In Safari using a cached element, getting the classname is 30x faster than using jQuery.<br/>
In Safari getting the element and then getting the classname is 35x faster than using jQuery.<br/>
</p>

<h3>Summary</h3>
<p>
	Whenever possible, using the browsers built in methods will always be faster, and just because you have a library available doesn't mean you should be using it for every DOM query. The speed advantage alone should dictate which methods of the library you are using and when.
</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/05/getting-a-class-from-a-dom-element/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing and Updating DOM Elements in a Frame</title>
		<link>http://scriptble.com/2011/02/writing-and-updating-dom-elements-in-a-frame/</link>
		<comments>http://scriptble.com/2011/02/writing-and-updating-dom-elements-in-a-frame/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 00:30:45 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[HTML]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=158</guid>
		<description><![CDATA[Handling writing and updating objects in an iframe can be bothersome in most browsers. Sure things like jQuery tend to help, but not always. A normal way to access a frame in jQuery is below: $("#FRAME").contents() Now, lets say you actually want to get another element inside of the frame, lets get the HEAD element. [...]]]></description>
			<content:encoded><![CDATA[<p>Handling writing and updating objects in an iframe can be bothersome in most browsers. Sure things like jQuery tend to help, but not always.</p>

<p>A normal way to access a frame in jQuery is below:</p>

<code class="language-javascript">
	$("#FRAME").contents()
</code>
<br/>

<p>Now, lets say you actually want to get another element inside of the frame, lets get the HEAD element.</p>

<code class="language-javascript">
	$("#FRAME").contents().find("HEAD");
</code>
<br/>
<span id="more-158"></span>
<p>Awesome, we now have the head element of the document in the frame. Lets add a style tag to it.</p>

<code class="language-javascript">
	$("#FRAME").contents().find("HEAD").append('<style type="text/css">BODY { background-color: green; }</style>');
</code>
<br/>

<p>Now this worked in most browsers... I say most for a reason. This was an actual use case I was trying to accomplish. However, good ole' IE wouldn't let me actually add a DOM element 
anywhere in the frame. The only thing I was able to do was to add in style tags on the elements. So how did I get around it?</p>

<code class="language-javascript">
	var ifrm;
		
	function addElementToFrame(newStyle) {
		if (typeof ifrm == "undefined"){
			ifrm = document.getElementById('previewFrame');
			if (ifrm.contentWindow){
				ifrm = ifrm.contentWindow;
			}else{
				if (ifrm.contentDocument.document){
					ifrm = ifrm.contentDocument.document;
				}else{
					ifrm = ifrm.contentDocument;
				}
			}
		}
		
		/*
		 * Now that we have the document, lets add a new style tag
		 */
		$("HEAD", ifrm.document).append("<style id='tempTag'>" + newStyle + "</style>");
		
	}
</code>
<br/>

<p>Wow, interesting mix of using straight JavaScript and jQuery in there. However, what happens when I want to just update the same style tag with something new?</p>

<code class="language-javascript">
	var ifrm;
		
	function addElementToFrame(newStyle) {
		if (typeof ifrm == "undefined"){
			ifrm = document.getElementById('previewFrame');
			if (ifrm.contentWindow){
				ifrm = ifrm.contentWindow;
			}else{
				if (ifrm.contentDocument.document){
					ifrm = ifrm.contentDocument.document;
				}else{
					ifrm = ifrm.contentDocument;
				}
			}
		}
		
		/*
		 * Now that we have the document, look for an existing style tag
		 */
		var tag = ifrm.document.getElementById("tempTag");
		
		/*
		 * Hmm, this doesn't look right, but it is. IE will not allow you 
		 * to use a pre-existing style tag and set the innerHTML for that 
		 * element. Which means, we can't create the style tag in another
		 * function and pass back the element and then set the innerHTML 
		 * to what we need. Plus, with this limitation, now we need to 
		 * actually remove the style element from the DOM and recreate 
		 * it each time. LAME.
		 */
		if (typeof tag != "undefined" || tag != null){
			$("#tempTag", ifrm.document).remove();
		}
		
		/*
		 * We only have one shot at writing out the style tag, we must 
		 * include the css at that point as well or IE will bail with an
		 * unsuported method exception.
		 *
		 * add a new style tag
		 */
		$("HEAD", ifrm.document).append("<style id='tempTag'>" + newStyle + "</style>");
	}
</code>
<br/>

<p>And that is how you can add new elements to a DOM in an iframe inside of your page.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/writing-and-updating-dom-elements-in-a-frame/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Expanding the jQuery Plugin Development Pattern</title>
		<link>http://scriptble.com/2011/02/expanding-the-jquery-plugin-development-pattern/</link>
		<comments>http://scriptble.com/2011/02/expanding-the-jquery-plugin-development-pattern/#comments</comments>
		<pubDate>Tue, 15 Feb 2011 01:00:25 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=151</guid>
		<description><![CDATA[Doing research on a recent project, I came across an article by Mike Alsup on a "jQuery Plugin Development Pattern". If you haven't seen it already its worth a trip to learningjquery.com to checkout the implementation of his pattern. "There are a few requirements that I feel this pattern handles nicely:" Claim only a single [...]]]></description>
			<content:encoded><![CDATA[<p>
	Doing research on a recent project, I came across an article by Mike Alsup on a <a href="http://www.learningjquery.com/2007/10/a-plugin-development-pattern">"jQuery Plugin Development Pattern"</a>. 
	If you haven't seen it already its worth a trip to learningjquery.com to checkout the implementation of his pattern.
</p>

<blockquote>
"There are a few requirements that I feel this pattern handles nicely:"

<ol>
   <li>Claim only a single name in the jQuery namespace</li>
   <li>Accept an options argument to control plugin behavior</li>
   <li>-Provide public access to default plugin settings-</li>
   <li>Provide public access to secondary functions (as applicable)</li>
   <li>Keep private functions private</li>
   <li>Support the Metadata Plugin</li>
   <li>Allow for extending the object via callbacks (either hooks or events) as applicable</li>
   <li>Scope all selectors with the 'this' object</li>
</ol>

</blockquote>
<br/>
<span id="more-151"></span>
<p>
	This is a great start to "authoring a jQuery plugin":http://docs.jquery.com/Plugins/Authoring. However, there are a couple more requirements that I would propse adding in.
</p>

<ol>
   <li>Claim only a single name in the jQuery namespace</li>
   <li>Accept an options argument to control plugin behavior</li>
   <li>-Provide public access to default plugin settings-</li>
   <li>Provide public access to secondary functions (as applicable)</li>
   <li>Keep private functions private</li>
   <li>Support the Metadata Plugin</li>
   <li>**Allow for extending the object via callbacks (either hooks or events) as applicable**</li>
   <li>**Scope all selectors with the 'this' object**</li>
</ol>

<br/>
<p>
	So lets take a look at how we can implement this pattern using a tab plugin.
</p>

<br/>
<h4>Claim Only a single name in the jQuery namespace</h4>
<br/>
<p>
	Setting up a new plugin is pretty simple. First we need to add the plugin name to the jQuery.fn namespace.
</p>

<code class="language-javascript">
	;(function($){
	})(jQuery);
</code>
<br/>
<p>
	Notice that We scope the setup of this plugin inside of an anonymous function that executes with the jQuery parameter as $. We do this so that the jQuery namespace can be changed in order to play well with other 
	javascript frameworks. It also allows us to scope jQuery to $ incase the namespace has already been changed.
</p>

<p>
	Next we need to setup the single namespace for our plugin.
</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
			}
        }
	})(jQuery);
</code>
<br/>
<p>
	Notice we setup the name of our plugin into the jQuery.fn namespace. Also, we add in a bit of trickery.  We need to make sure that if this plugin is called on multiple DOM elements, that it will still function properly. 
	We do this by looping through each of the elements and calling .carousel() on them. We then return "this" in order to allow chaining of methods.
</p>

<code class="language-javascript">
        // support mutltiple elements
        if (this.length > 1){
            this.each(function() { $(this).tabs(tabOptions) });
            return this;
		}
</code>
<br/>

<h4>Accept an options argument to control plugin behavior</h4>
<br/>
<p>
	By creating an options argument, we can allow the users to expand/change the default behavior of the plugin. The following code adds in a newOptions parameter and then uses jQuerys 
	built in $.extend to override the default plugin options.
</p>

<code class="language-javascript">
	;(function($){
    $.fn.tabs = function(tabOptions) {
        // support mutltiple elements
        if (this.length > 1){
            this.each(function() { $(this).tabs(tabOptions) });
            return this;
        }

        // SETUP private variabls;
        var tabs = this;

        // setup options
        var defaultOptions = {
								//default options go here.
                                };
								
        var options = $.extend({}, defaultOptions, tabOptions);

        return this;
    }
})(jQuery);

</code>
<br/>
<p>
	Notice the following code it expands the default options:
</p>

<code class="language-javascript">
        var options = $.extend({}, defaultOptions, tabOptions);
</code>
<br/>

<h4>Provide public access to secondary functions (as applicable)</h4>
<br/>
<p>
	We can give access to public functions by attching the functions to the magic variable "this". 
</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
	        }
	
	        // SETUP private variabls;
	        var tabs = this;
	
	        // setup options
	        var defaultOptions = {
	                                    debug : false
	                                };
	        var options = $.extend({}, defaultOptions, tabOptions);


			// PUBLIC functions
	        this.changeTab = function() {
	            // change Tab
	        };
	
	        this.getOptions = function() {
	            return options;
	        };

	
	        return this;
	    }
	})(jQuery);

</code>
<br/>

<h4>Keep private functions private</h4>
<br/>
<p>
	Private functions setup in the way below can only be called from within the scope that they were created. What this means is that there is no outside access to these functions. They can only be called 
	from within another public methods or another private methods. In order to access this data we would need to setup public methods to call these private methods.
</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
	        }
	
	        // SETUP private variabls;
	        var tabs = this;
	
	        // setup options
	        var defaultOptions = {
	                                    debug : false
	                                };
	        var options = $.extend({}, defaultOptions, tabOptions);

	        // SETUP private functions;
	        var intialize = function() {
					return tabs;
	        };
			
	        var findTabs = function() {
	                                // do something .
	                            };
								
			var selectTab = function(element, tabCSS, selectedClass){
									// do something .
								};
								
	        var hooks = function() {
	                                // do something .
	                            };
			
			// PUBLIC functions
	        this.changeTab = function() {
	            // change Tab
	        };
	
	        this.getOptions = function() {
	            return options;
	        };
	
	        return intialize();
	    }
	})(jQuery);

</code>
<br/>


<h4>Support the Metadata Plugin</h4>
<br/>
<p>Supporting the Metadata plugin is fairly trivial. We test for the existence of the plugin and then add the data that would be attached to the element.</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
	        }
	
	        // SETUP private variabls;
	        var tabs = this;
	
	        // setup options
	        var defaultOptions = {
	                                    debug : false
	                                };
	        var options = $.extend({}, defaultOptions, tabOptions);

	        // SETUP private functions;
	        var intialize = function() {
	                // support MetaData plugin
	                if ($.meta){
	                    options = $.extend({}, options, this.data());
	                }

					return tabs;
	        };
			
	        var findTabs = function() {
	                                // do something .
	                            };
								
			var selectTab = function(element, tabCSS, selectedClass){
									// do something .
								};
								
	        var hooks = function() {
	                                // do something .
	                            };
			
			// PUBLIC functions
	        this.changeTab = function() {
	            // change Tab
	        };
	
	        this.getOptions = function() {
	            return options;
	        };
	
	        return intialize();
	    }
	})(jQuery);

</code>
<br/>
<h4>Allow for extending the object via callbacks (either hooks and/or events)</h4>
<br/>
<p>
	In order to do this, lets take a more in depth look at the changeTab function. 
	It sounds complicated, however its a trivial task to setup and allow the moveSlider functionality to be altered by the external options.
</p>

<code class="language-javascript">
	// PUBLIC functions
    this.changeTab = function() {
        // change Tab
    };
</code>
<br/>

<p>In order to alter the behavior we need to allow the user to pass in some options.</p>

<code class="language-javascript">
    // setup options
    var defaultOptions = {
								beforeLoad : function() {
												// do something .
											},
								afterLoad : function() {
												// do something .
											},
                                debug : false
                            };
</code>
<br/>
<p>Now, lets update hooks function to see what needs to be done in order to call the function.</p>

<code class="language-javascript">	   
        var hooks = function(thisObject, hookList, triggerName){
            $(presentation).trigger(triggerName, thisObject);
            if ($.isFunction(hookList)){
                return hookList.apply(thisObject, []).isOK;
            } else if ($.isArray(hookList)) {
                var result = {
                    isOK: true
                };
                for (var i = 0; i < hookList.length; i++) {
                    if (result.isOK) {
                        result = hookList[i].apply(thisObject, [ result.data ]);
                    }
                }
                return result.isOK;
            }else{
                return true;
            }
        }
</code>
<br/>
<p>What exactly is this doing? First of all the hooks function takes 3 parameters. thisObject is equal to the object that you want the callback function to have "this" set to, 
a method to call back on called hookList and the name of the event to be triggered. The reason we call it list, is that we will check to see if hookList is an array of 
functions or just a single function. The following call passes in the tabs object and the onstart callbacks.</p>

<p>Now, lets change the this.changeTab to make use of the beforeLoad and afterLoad events.</p>


<code class="language-javascript">
	this.changeTab = function(element){
		if (hooks(tabs, options.beforeLoad, "beforeLoad")){
			selectTab(element, options.tabsClass, options.tabsSelected);
			
			var tabOptions = {};
			if (options['tab' + tabs.mainTab] != undefined) {
				tabOptions = options['tab' + tabs.mainTab];
			}
			
			$(options.tabPanels, this).hide();
			
			if (options.afterLoad != undefined) {
				hooks(tabs, options.afterLoad, "afterLoad")
			} else {
				$('.tab' + tabs.mainTab, this).show();
			}
		}
	};
</code>
<br/>

<p>In the hooks method we use the .apply in order to pass "this" as the plugin to the next function. They will have access to all of the public methods that are on that instance of the tabs plugin.</p>


<h4>Scope all selectors with the 'this' object</h4>
<br/>
<p>This is actually really simple, but will control the scope of the objects returned by jQuery. Without this, you may clobber another widget on the page or jump outside of the element you are working on. 
Lets take another look at the selectTab method and see how we can scope our selectors.</p>

<code class="language-javascript">
         var selectTab = function(element, tabCSS, selectedClass){
              var selectedTab = 0;
              selectedClass = selectedClass.replace(/^./, "");
              $(tabCSS).each(function(){
                   if (this == element) {
                        tabs.mainTab = selectedTab;
                        $(element).addClass(selectedClass);
                   } else {
                        $(this).removeClass(selectedClass);
                   }
                   selectedTab++;
              });
         };

</code>
<br/>
<p>On the surface, there is nothing wrong with this. However, what happens if we have two different tab groups on the page? Nothing? How about an extremely large DOM? Would this slow down? Yes, actually it would 
and you may or may not be acting on a set of tabs that aren't your own.</p>

<p>So how do we fix this?</p>

<code class="language-javascript">
         var selectTab = function(element, tabCSS, selectedClass){
              var selectedTab = 0;
              selectedClass = selectedClass.replace(/^./, "");
              $(tabCSS, tabs).each(function(){
                   if (this == element) {
                        tabs.mainTab = selectedTab;
                        $(element).addClass(selectedClass);
                   } else {
                        $(this).removeClass(selectedClass);
                   }
                   selectedTab++;
              });
         };
</code>
<br/>
<p>Wait, that is the same code? Close, but look closer at the $(tabCSS) selector. Notice, we now use $(tabCSS, tabs). (<a href="/2011/02/the-great-assumption-javascript/">You could also use $(tabs).find(tabCSS); is faster in most browsers</a>). 
This limits the scope of the search for the tabs and it won't clobber any other tab widgets on the page.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/expanding-the-jquery-plugin-development-pattern/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>jQuery 1.5 Deferreds</title>
		<link>http://scriptble.com/2011/02/jquery-1-5-deferreds/</link>
		<comments>http://scriptble.com/2011/02/jquery-1-5-deferreds/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 02:59:18 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Underscore.JS]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=144</guid>
		<description><![CDATA[Eric Hynds on his blog the other day gave a very good run down of jQuery 1.5 Deferreds. From the post: Deferreds, new in jQuery 1.5, decouple logic dependent on the outcome of a task from the task itself. They’re nothing new to the JavaScript scene; Mochikit and Dojo have implemented them for some time, [...]]]></description>
			<content:encoded><![CDATA[</p>
<a href="http://www.erichynds.com/jquery/using-deferreds-in-jquery/">Eric Hynds</a> on his blog the other day gave a very good run down of jQuery 1.5 Deferreds. From the post:
<p>
</br>
<blockquote>Deferreds, new in jQuery 1.5, decouple logic dependent on the outcome of  a task from the task itself.  They’re nothing new to the JavaScript  scene; Mochikit and Dojo have implemented them for some time, but with <a href="http://jaubourg.net/">Julian Aubourg’s</a> AJAX rewrite landing in 1.5, deferreds in jQuery was the logical next  step.  With deferreds, multiple callbacks can be bound to a task’s  outcome, and any of these callbacks can be bound even after the task is  complete.  The task in question may be asynchronous, but not  necessarily.</blockquote>
<br/>
<span id="more-144"></span>
<p>Especially nice is being able to couple multiple statements and once they finish being able to go on to the next step.</p>
<p>In the following example, we retrieve JSON data and a separate template, once the calls finish we move onto rendering them using Underscore.js templating.</p>
</br>
<code class="language-javascript">
var JSONData = {};
var template = "";
function loadData(data){
     JSONData = data;
}

function loadTemplate(data){
     template = data;
}

function render {
     var output = _.template(template, { employeeList : employeeList } );
     $(document.getElementById("output")).html(output);
}

$.when(
     $.getJSON("JSONData").success(loadData), 
     $.get("template.tmpl").success(loadTemplate)
).then(
   render
);
</code>
<br/>
<p>
Deferreds in jQuery is step in the right direction and adds in some very nice functionality to an already feature rich library.
</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/jquery-1-5-deferreds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>$(&#8220;#ID&#8221;) is fast enough</title>
		<link>http://scriptble.com/2011/02/jquery-id-is-fast-enough/</link>
		<comments>http://scriptble.com/2011/02/jquery-id-is-fast-enough/#comments</comments>
		<pubDate>Sat, 12 Feb 2011 22:22:38 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[Do This, Not That]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=129</guid>
		<description><![CDATA[We all know that the fastest selector to use is the ID. Something like $("#id") is better than using a class. However, after looking at the last test we did on The Great Assumption - JavaScript I noticed a large discrepancy in $("#ID") versus the native document.getElementById(). Now, I always assumed it was slower, but [...]]]></description>
			<content:encoded><![CDATA[<section id="assumption">
	<p>
		We all know that the fastest selector to use is the ID. Something like $("#id") is better than using a class. However, 
		after looking at the last test we did on <a href="/2011/02/the-great-assumption-javascript/">The Great Assumption - JavaScript</a> I noticed 
		a large discrepancy in $("#ID") versus the native document.getElementById().
	</p>
	
	<p>
		Now, I always assumed it was slower, but not anywhere near close to what I saw. So, lets challenge the assumption that $("#ID") is good enough.
	</p>
</section>
<span id="more-129"></span>

<section id="testSetup">
	<h3>Setting up the Test</h3>
	<br/>
	<p>
		You can see the test here: <a href="http://jsperf.com/getelement-versus-id">JSPerf $(doc.getElementById()) versus $("#id")</a>
	</p>
	<p>
		I wanted to test 3 of the latest versions of jQuery, same as the last test. I added the following to the test:
	</p>
	
	<code class="language-html">
&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
var $15 = jQuery.noConflict();
&lt;/script&gt;

&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
var $144 = jQuery.noConflict();
&lt;/script&gt;

&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
var $142 = jQuery.noConflict();
&lt;/script&gt;


&lt;div class="wrapper"&gt;
     &lt;div class="innerWrapper"&gt;
          &lt;div class="button"&gt;
               &lt;a href="javascript:void(0)" id="button" class="buttonRef"&gt;
                    &lt;span class="buttonText"&gt;Text&lt;/span&gt;
               &lt;/a&gt;
          &lt;/div&gt;
     &lt;/div&gt;
&lt;/div&gt;
	</code>
</section>
<br/>

<section id="theTests">
	<h5>The Tests</h5>
	<br/>
	<p>
		So lets setup the actual tests:
	</p>
	
	<code class="language-javascript">
		//getElement - 1.4.2
		$142(document.getElementById("button"));
		
		//ID - 1.4.2
		$142("#button");
		
		
		//getElement - 1.4.4
		$144(document.getElementById("button"));

		//ID - 1.4.2
		$144("#button");
		
		//getElement - 1.5
		$15(document.getElementById("button"));
		
		//ID - 1.4.2
		$15("#button");
	</code>
	<br/>
	<p>
		Each one of the tests above will run and the result will be returned in Ops/Sec. 
	</p>
</section>
<br/>
<section id="Results">
	<h5>Results</h5>
	<br/>
	<p>After runs in all different versions of the browsers we have a fairly good idea of the results. Take a look below.</p>
	<br/>
	<iframe src="http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnINCxIEVGVzdBien6wEDA?o=html&v=3" style="width: 648px; height: 530px;"></iframe>
</section>
<br/><br/><br/>
<section id="ResultsNative">
	<h5>Native Browser Call Results</h5>
	<br/>
	<img src="/images/hybridID/nativeGetID.png" />
	<br/><br/>
	<p>
		From the last test we know that getting a Node Element from the native browser call is suprisingly efficient and fast in many browsers. Well, that is unless you are using IE 6, 7, 8 or even the beta 9.
	</p>
</section>
<br/>
<section id="ResultsjQuery">
	<h5>jQuery $("#ID") Results</h5>
	<br/>
	<img src="/images/hybridID/jqueryID.png" />
	<br/><br/>
	<p>
		The results from this test show that getting an ID using jQuery is much faster than using the class selector. However, it is way behind the native call.
		The root cause of this is actually due to how the init function is configured. Looking at the source for 1.5, an ID selector will hit 6 IF statements, plus 
		1 regex before it makes the native document.getElementByID(). After the call, there is a series of browser compatibility checks before it assigns the Node 
		Element to the jQuery object and returns.
	</p>
	<code class="language-javascript">
init: function( selector, context ) {
	var match, elem, ret, doc;

	// Handle $(""), $(null), or $(undefined)
	if ( !selector ) {
		return this;
	}

	// Handle $(DOMElement)
	if ( selector.nodeType ) {
		this.context = this[0] = selector;
		this.length = 1;
		return this;
	}
	
	// The body element only exists once, optimize finding it
	if ( selector === "body" && !context && document.body ) {
		this.context = document;
		this[0] = document.body;
		this.selector = "body";
		this.length = 1;
		return this;
	}

	// Handle HTML strings
	if ( typeof selector === "string" ) {
		// Are we dealing with HTML string or an ID?
		match = quickExpr.exec( selector );

		// Verify a match, and that no context was specified for #id
		if ( match && (match[1] || !context) ) {

			// HANDLE: $(html) -> $(array)
			if ( match[1] ) {
				doc = (context ? context.ownerDocument || context : document);

				// If a single string is passed in and it's a single tag
				// just do a createElement and skip the rest
				ret = rsingleTag.exec( selector );

				if ( ret ) {
					if ( jQuery.isPlainObject( context ) ) {
						selector = [ document.createElement( ret[1] ) ];
						jQuery.fn.attr.call( selector, context, true );

					} else {
						selector = [ doc.createElement( ret[1] ) ];
					}

				} else {
					ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
					selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
				}
				
				return jQuery.merge( this, selector );
				
			// HANDLE: $("#id")
			} else {
				elem = document.getElementById( match[2] );

				// Check parentNode to catch when Blackberry 4.6 returns
				// nodes that are no longer in the document #6963
				if ( elem && elem.parentNode ) {
					// Handle the case where IE and Opera return items
					// by name instead of ID
					if ( elem.id !== match[2] ) {
						return rootjQuery.find( selector );
					}

					// Otherwise, we inject the element directly into the jQuery object
					this.length = 1;
					this[0] = elem;
				}

				this.context = document;
				this.selector = selector;
				return this;
			}

		// HANDLE: $("TAG")
		} else if ( !context && !rnonword.test( selector ) ) {
			this.selector = selector;
			this.context = document;
			selector = document.getElementsByTagName( selector );
			return jQuery.merge( this, selector );

		// HANDLE: $(expr, $(...))
		} else if ( !context || context.jquery ) {
			return (context || rootjQuery).find( selector );

		// HANDLE: $(expr, context)
		// (which is just equivalent to: $(context).find(expr)
		} else {
			return jQuery( context ).find( selector );
		}

	// HANDLE: $(function)
	// Shortcut for document ready
	} else if ( jQuery.isFunction( selector ) ) {
		return rootjQuery.ready( selector );
	}

	if (selector.selector !== undefined) {
		this.selector = selector.selector;
		this.context = selector.context;
	}

	return jQuery.makeArray( selector, this );
},
	</code>
	<br/>
	<p>
		Notice the elem = document.getElementById( match[2] ) on line 58. This is the part where it delegates its call to the native function.
	</p>
	<p>
		HOWEVER, what is that on line 9? A use case for $(DOMElement)? Why yes, yes it is, and that leads us to the next test.
	</p>
</section>
<br/>
<section id="ResultsHyrbid">
	<h5>Hybrid Results</h5>
	<br/>
	<img src="/images/hybridID/hybrid.png" />
	<br/><br/>
	<p>
		So by selecting the DOM Element, and passing it into to jQuery we have achieved nearly 100% or more increase in speed across all browsers (except IE). IE still benefits from this method, it had a 49% increase 
		in operations per second.
	</p>
</section>
<br/>
<section id="ResultsTogether">
	<h5>Hybrid Results</h5>
	<br/>
	<img src="/images/hybridID/allTogether.png" />
	<br/><br/>
	<p>
		Here you can clearly see that by using a hybrid solution we have achieve a significant amount of gain over using the built 
		in jQuery ID selector. Its not nearly as fast, but allows us to benefit from the built-in functions of jQuery and speed up the 
		operation.
	</p>
</section>
<br/>
<section id="Conclusion">
	<h3>Do This, Not That</h3>
	<br/>
	<p>
		Not exactly what I expected when I set out on this one. However I think we have a clear winner. IF you are using jQuery, pass the node Element in, other wise just use the native getElementById().
	</p>
	<h6>Conclusion</h6>
	<p><strong>Do This</strong></p>
	<code class="language-javascript">
		$(document.getElementById("someId"));
	</code>
	<br/>
	<p><strong>Not That</strong></p>
	<code class="language-javascript">
		$("#someId");
	</code>
</section>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/jquery-id-is-fast-enough/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Great Assumption &#8211; Javascript</title>
		<link>http://scriptble.com/2011/02/the-great-assumption-javascript/</link>
		<comments>http://scriptble.com/2011/02/the-great-assumption-javascript/#comments</comments>
		<pubDate>Fri, 11 Feb 2011 04:52:28 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[Do This, Not That]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=115</guid>
		<description><![CDATA[A couple of weeks ago I was sitting down with a Google Frontend Engineer friend of mine, talking about some of the JavaScript best practices we all have come to know and abide by. I found myself in agreement with 90% of everything we were talking about. However, something kept eating at me. Why do [...]]]></description>
			<content:encoded><![CDATA[<section id="greatAssumption">
	<p>
		A couple of weeks ago I was sitting down with a Google Frontend Engineer friend of mine, talking about some of the JavaScript best practices we all have come to know and abide by. I found myself in agreement with 90% of everything we were talking about. However, something kept eating at me. Why do we both agree on these things? Is it because we actually sat down and did some test? Or is more because early in our careers we were told it was the correct way and have never gone about challenging our assumptions.
	</p>
	<p>
		So with this post, I am going to start challenging our assumptions on what's right, OR validate those assumptions with some documented proof. Thus begins our first in a series of posts about performance, and a "Do this, Not that" series. Some of the posts will focus on jQuery, others on core JavaScript, however all of them should give you some insight on what to do in the future.
	</p>
</section>
<span id="more-115"></span>
<br/>
<section id="assumption">
	<h2>Find Versus Context</h2>
	<br/>
	<p>
		Everyone has heard that we should scope our requests in jQuery to make sure and only return results that we are looking for. This is especially true if we are writing a plugin. And lately I have been hearing we should be using .find() to get the elements we are looking for. 
	</p>
	<p>
		Of course, that peaked my interest. Why use .find() which I had heard was slower, than using $("", context) which scopes the call in much the same way in jQuery. So I set off to write a Performance Test that would check to see which one I should be using.
	</p>
</section>

<section id="testSetup">
	<h5>Setting up the Test</h5>
	<br/>
	<p>
		You can see the test here: <a href="http://jsperf.com/jquery-find-versus-context-versions-1-4-2-to-1-5">JSPerf jQuery Find Versus Context versions 1-4-2 to 1-5</a>
	</p>
	<p>
		I wanted to test 3 of the latest versions of jQuery, plus the browsers native docuemnt.getElementById(). so I added the following to the test:
	</p>
	
	<code class="language-html">
		&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"&gt;&lt;/script&gt;
		&lt;script type="text/javascript"&gt;
		var $15 = jQuery.noConflict();
		&lt;/script&gt;

		&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js"&gt;&lt;/script&gt;
		&lt;script type="text/javascript"&gt;
		var $144 = jQuery.noConflict();
		&lt;/script&gt;

		&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
		&lt;script type="text/javascript"&gt;
		var $142 = jQuery.noConflict();
		&lt;/script&gt;


		&lt;div class="wrapper"&gt;
		     &lt;div class="innerWrapper"&gt;
		          &lt;div class="button"&gt;
		               &lt;a href="javascript:void(0)" id="button" class="buttonRef"&gt;
		                    &lt;span class="buttonText"&gt;Text&lt;/span&gt;
		               &lt;/a&gt;
		          &lt;/div&gt;
		     &lt;/div&gt;
		&lt;/div&gt;
		&lt;script&gt;
		 var context5 = $15("div.wrapper");
		 var context44 = $144("div.wrapper");
		 var context42 = $142("div.wrapper");
		&lt;/script&gt;
	</code>
	<br/>
	<p>
		Notice that I am going to set a variable for each of the individual jQuery versions. This allows me to use multiple version in the noConflict() state. (They won't overwrite each other and I will be able to have all of them on the same page.) Also, I setup a couple of variables that I want to cache the results. If we had to call this for each of the tests, we wouldn't get an accurate result between a find and context search.
	</p>
</section>

<section id="theTests">
	<h5>The Tests</h5>
	<br/>
	<p>
		So lets setup the actual tests:
	</p>
	
	<code class="language-javascript">
	//Get - document
	var item = document.getElementById("button");

	//Get - ID 1.4.2
	var item = $142("#button");

	//Get - ID 1.4.4
	var item = $144("#button");

	//Get - ID 1.5
	var item = $15("#button");

	//Context - ID 1.4.2
	var item = $142("#button", context42);

	//Context - ID 1.4.4
	var item = $144("#button", context44);

	//Context - ID 1.5
	var item = $15("#button", context5);

	//Find - ID 1.4.2
	var item = context42.find("#button")

	//Find - ID 1.4.4
	var item = context44.find("#button")

	//Find - ID 1.5
	var item = context5.find("#button")

	//Get - Class 1.4.2
	var item = $142(".buttonRef");

	//Get - Class 1.4.4
	var item = $144(".buttonRef");

	//Get - Class 1.5
	var item = $15(".buttonRef");

	//Context - Class 1.4.2
	var item = $142(".buttonRef", context42);

	//Context - Class 1.4.4
	var item = $144(".buttonRef", context44);

	//Context - Class 1.5
	var item = $15(".buttonRef", context5);

	//Find - Class 1.4.2
	var item = context42.find(".buttonRef")

	//Find - Class 1.4.4
	var item = context44.find(".buttonRef")

	//Find - Class 1.5
	var item = context5.find(".buttonRef")

	</code>
	<br/>
	<p>
		Each one of the tests above will run and the result will be returned in Ops/Sec. At this point, we are going to run a test to figure out how fast a context.find(""), $("", context) take for an ID and for a class. I also added in a default document.getElementById() to test how fast natively the browser is able to get a Node Element.
	</p>
</section>

<section id="Results">
	<h5>Results</h5>
	<br/>
	<p>After runs in all different versions of the browsers we have a fairly good idea of the results. Take a look below.</p>
	<br/>
	<iframe src="http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnINCxIEVGVzdBjti6cEDA?o=html&v=3" style="width: 648px; height: 670px;"></iframe>
</section>
<br/><br/><br/>
<section id="ResultsClass">
	<h5>Find a class element Results</h5>
	<br/>
	<img src="/images/findVersusContext/classChart.png" />
	<br/><br/>
	<p>
		In General this test held true. Using find in all but FF3 and Opera is a faster way to find an element using a class.
	</p>
	<h6>Conclusion</h6>
	<p><strong>Do This</strong></p>
	<code class="language-javascript">
		context.find(".someclass");
	</code>
	<br/>
	<p>Not That</p>
	<code class="language-javascript">
		$(".someclass");
	</code>
</section>
<br/>
<section id="ResultsId">
	<h5>Find an element by ID Results</h5>
	<br/>
	<img src="/images/findVersusContext/idChart.png" />
	<br/>
	<br/>
	<p>
		WOW, not what I expected. Not one browse was a find faster than just using $("#someID"). Basically this all boils down to how jQuery treats an ID selector. It doesn't use the sizzle engine to query the Node Element, but uses the browsers built in document.getElementById(). However, if you pass in a context jQuery will use the engine to make sure the element falls within the context you are using.
	</p>
	<h6>Conclusion</h6>
	<p><strong>Do This</strong></p>
	<code class="language-javascript">
		$("#someID");
	</code>
	<br/>
	<p><strong>Not That</strong></p>
	<code class="language-javascript">
		context.find("#someId");
		$("#someId", context);
	</code>
</section>
<br/>
<section id="ResultsId">
	<h5>Find an element using built in getElementById() Results</h5>
	<br/>
	<img src="/images/findVersusContext/byIdChart.png" />
	<br/>
	<br/>
	<p>
		Ok, so this result really confused me after seeing the jQuery $("#someID") results. I wasn't expecting there to be such a discrepancy in operations per second. After seeing this result, I actually started putting together another post. Which will end up the second part of this series.
	</p>
	<p>
		It should be noted that Chrome, Opera, Safari and FF are all doing well over a million operations per second in this area. 
	</p>
</section>
<br/>
<section id="ResultsId">
	<h5>IE breakdown</h5>
	<br/>
	<img src="/images/findVersusContext/ieChart.png" />
	<br/>
	<br/>
	<p>
		After seeing the results above, I thought we needed one more graphic showing the extremely bad numbers IE put up in this test. There was no noticable change between IE6 and IE7, and while IE8 is better, its still bad. However, it looks like the IE9 team is finally taking web development seriously and trying to make some improvements. Of course those improvements still fall WAY short of any of the other browsers on the market.
	</p>
	<p>
		Come on IE team, haven't we learned anything from the IE6 debacle?
	</p>
</section>
<br/>
<section id="conclusion">
	<h5>Conclusion</h5>
	<br/>
	<p>
		Overall, the conlusion here is to never use a context based find/search for an ID. (since there is always only one on the page... right?) If you need to get an element using an ID, just call it via $("#someID").
	</p>
	<p>
		IF you need to get a class element(s), follow this rule:<br/>
		context.find() &gt; $(".someClass", context) &gt; $(".someclass");
	</p>
</section>
<p>
Next Article &gt;&gt; <a href="/2011/02/jquery-id-is-fast-enough/">$(“#ID”) is fast enough</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/the-great-assumption-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Performance Testing &#8211; An Indispensable Tool</title>
		<link>http://scriptble.com/2011/02/javascript-performance-testing-an-indispensable-tool-2/</link>
		<comments>http://scriptble.com/2011/02/javascript-performance-testing-an-indispensable-tool-2/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 05:36:23 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[Performance]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=100</guid>
		<description><![CDATA[Over the course of the last couple of weeks I have been looking into various tools to test Javascript Pefromance. I needed a way to test various JavaScript code snippets to see the overall latency/run time of each. I started looking for a way to manage the tests and be able to reference them in [...]]]></description>
			<content:encoded><![CDATA[<p>Over the course of the last couple of weeks I have been looking into various tools to test Javascript Pefromance. I needed a way to test various JavaScript code snippets to see the overall latency/run time of each. I started looking for a way to manage the tests and be able to reference them in an easy way. Here are a couple of the performance suites I looked at and afterwards, my decision.</p>
<p><span id="more-100"></span></p>
<h3>JSLitmus</h3>
<p>You can find the source for <a title="JSLitmus" href="http://www.broofa.com/Tools/JSLitmus/" target="_self">JSLitmus</a> here. It has a great set of features and allows you to install it on your own site. So here are some pros and cons I found when setting up JSLitmus.</p>
<p><b>Pros:</b></p>
<ul>
<li>Single-file install (<a href="http://www.broofa.com/Tools/JSLitmus/JSLitmus.js">JSLitmus.js</a>)</li>
<li>Works on Firefox, Opera, Safari, IE, Google Chrome, and iPhone browsers</li>
<li>Adaptive test cycles &#8211; tests take ~1-2 seconds, regardless of the operation</li>
<li>Google Chart + TinyUrl integration</li>
<li>Open Source MIT-style license (see source)</li>
</ul>
<p>source: &lt;<a href="http://www.broofa.com/Tools/JSLitmus/">http://www.broofa.com/Tools/JSLitmus/</a>&gt;</p>
<p><b>Cons:</b></p>
<ul>
<li>Need to host this on your own server.</li>
<li>Need a place to save off/Manage existing Tests.</li>
<li>Some tests report &#8220;Infinity&#8221; when run, which meant that the tests were executing so fast that it couldn&#8217;t get an accurate read on the total OPS/Sec.</li>
</ul>
<p><b>Conclusion:</b></p>
<p>JSLitmus is a nice set of tools. If you have access to your own host and are able to put together a way to manage the tests, I would recommend this is a possible solution. However, I did not go with this solution.</p>
<h3>JSPerf</h3>
<p>I found <a title="jsPerf.com" href="http://jsperf.com" target="_self">JSPerf.com</a> after digging through the posts that Paul Irish&#8217;s put together about jQuery. <a title="10 Things I Learned from the jQuery Source" href="http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/">10 Things I Learned from the jQuery Source</a> and <a title="11 More Things I Learned from the jQuery Source" href="http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/">11 More Things I Learned from the jQuery Source</a>. If you haven&#8217;t had a chance to read those, I highly recommend them, they help to give you a bit more information on whats going on in jQuery. They are also what lead me down the path to figure out why certain queries are slower than others, but thats another post all together.</p>
<p><b>Pros:</b></p>
<ul>
<li>JSPerf is based on <a title="benchmark.js" href="http://benchmarkjs.com/">benchmark.js</a> a very powerful performance testing suite.</li>
<li>Has an online environment to store and test JS</li>
<li>You can download the source and run it on your own host.</li>
<li>You can browse through other <a title="browse performance tests" href="http://jsperf.com/browse">peoples tests</a>, make changes and save copies.</li>
<li>You can see most <a title="popular tests" href="http://jsperf.com/popular">popular tests</a></li>
<li>Has quick links to embed common JS frameworks</li>
<li>Uses a java jar to refine time calculations rather than just relying on JavaScripts built in time.</li>
</ul>
<p><b>Cons:</b></p>
<ul>
<li>Browsing tests is a pain in the online tool</li>
<li>Saving a copy of a test just adds a revision number to the end of the url rather than allowing you to create a new url for the test.</li>
<li>Sometimes test runs aren&#8217;t saved off properly. I noticed this on my Mac using Safari 5.0.3</li>
</ul>
<p><b>Conclusion:</b></p>
<p>JSPerf seems to be able to handle all the aspects I need for everyday performance needs. I will be setting up a copy on this host, just so I can keep my own tests around and not need to bookmark them for reference later on.</p>
<h3>Conclusion</h3>
<p>Overall, I think JSPerf is the hands down winner at this point. Doesn&#8217;t mean I won&#8217;t find a better solution down the road, but for now, being able to quickly write a test on jsPerf and just run it to see how well it performs is much easier than hosting my own performance suite.</p>
<p>In the next couple of days I will be posting some of my performance test runs and some of the conclusions based on those results.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/javascript-performance-testing-an-indispensable-tool-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Underscore.js Templates</title>
		<link>http://scriptble.com/2011/01/underscore-js-templates/</link>
		<comments>http://scriptble.com/2011/01/underscore-js-templates/#comments</comments>
		<pubDate>Sat, 29 Jan 2011 00:00:54 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Underscore.JS]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[UnderScore.js]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=53</guid>
		<description><![CDATA[After the post about why Underscore.js, I think it is best to follow up on one of the best parts of the library. Now, I haven&#8217;t had a chance to go through the new templating in jQuery, however what I have found with Underscore.js has allowed me to complete some very complicated tasks in my [...]]]></description>
			<content:encoded><![CDATA[<p>After the post about why Underscore.js, I think it is best to follow up on one of the best parts of the library. Now, I haven&#8217;t had a chance to go through the new templating in jQuery, however what I have found with Underscore.js has allowed me to complete some very complicated tasks in my day to day work.</p>

<p>Lets take a look at the documentation for _.template and then we will dig into it a bit more:</p>

<blockquote>
    <p>template_.template(templateString, [context])<br />
    Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate variables, using</p>
    <p>&lt;%= ... %&gt;, as well as execute arbitrary JavaScript code, with &lt;% ... %&gt;. When you evaluate a template function, pass in a context object that has properties corresponding to the template&#8217;s free variables. If you&#8217;re writing a one-off, you can pass the context object as the second parameter to template in order to render immediately instead of returning a template function.</p>

    <code>
    var compiled = _.template("hello: <%= name %>");<br/>
    compiled({name : 'moe'});<br/>
    => "hello: moe"	<br />
    var list = "<% _.each(people, function(name) { %><br/>
    &lt;li&gt;<%= name %>&lt;/li&gt;<br /> 
    <% }); %>";<br/><br/>
    _.template(list, {people : ['moe', 'curly', 'larry']});<br/>
    => "<br/>
    &lt;li&gt;moe&lt;/li&gt;<br/>
    &lt;li&gt;curly&lt;/li&gt;<br/>
    &lt;li&gt;larry&lt;/li&gt;<br/>
    "<br/>
    </code>

    <p>Pasted from &lt;<a href="http://documentcloud.github.com/underscore/">http://documentcloud.github.com/underscore/</a>&gt;</p>
</blockquote>
<br />
<p>So what can we do with this? Lets take a look at showing some employee data:</p>
<span id="more-53"></span>

<h3>Standard Templating</h3>
<br>
<code class="language-javascript">
var employeeList = [
                        {
                            name     : "John smith",
                            position : "CEO",
                            pay      : 1,
                            hours    : 2020,
                            type     : "USD"
                        },
                        {
                            name     : "Jane Smith",
                            position : "CFO",
                            pay      : 2,
                            hours    : 2020,
                            type     : "USD"
                        },
                        {
                            name     : "Alex Smith",
                            position : "Lead Programmer",
                            pay      : 500,
                            hours    : 2020,
                            type     : "EUR"
                        }
                    ];
var template = "\
                &lt;table cellspacing='0' cellpadding='0' border='1' id='employee'&gt;\
                    &lt;tbody&gt;\
                        &lt;tr&gt;\
                            &lt;td&gt;Name&lt;/td&gt; \
                            &lt;td&gt;Position&lt;/td&gt; \
                            &lt;td&gt;Pay&lt;/td&gt; \
                            &lt;td&gt;Hours&lt;/td&gt; \
                            &lt;td&gt;Type&lt;/td&gt; \
                            &lt;td&gt;Total Compensation&lt;/td&gt; \
                        &lt;/tr&gt; \
                        <% for (var index = 0; index < employeeList.length; index++){ %>\
                            <% var employee = employeeList[index]; %>\
                            <% var compensation = employee.hours * employee.pay; %>\
                            &lt;tr&gt;\
                                &lt;td&gt;&lt;%= employee.name %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= employee.position %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= employee.pay %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= employee.hours %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= employee.type %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= compensation %&gt;&lt;/td&gt; \
                            &lt;/tr&gt; \
                        <% } %>\
                    &lt;/tbody&gt; \
                &lt;/table&gt; \
                ";
$(document).ready(function() {
    var output = _.template(template, { employeeList : employeeList } );
    $("#employeeContainer").html(output);
});
</code>
<br />
<br/>

<p>The corresponding output is below:</p>
<div id="employeeContainer"></div>
<br/>
<br />
<p>Now, if we were requesting the data from an Ajax call based on some parameters this would make it a bit more interesting, but you can get a feeling for how to take data and a view for that data and output something that actually makes sense.</p>


<p>So lets dig a bit more into the different tags, and why the \ is on each line.</p>

<ol type="1">
    <li>JavaScript does not handle multiple line strings (why, no idea but it would be really helpful to have multi line strings. Even if they used something like the perl EOF delimiter to figure out where the end of the string should be, but I digress). In order to have a multi-line string, we need to add the \ (backslash) to the end of each line to tell the JavaScript parser that there is more on the next line.</li>
    <li>Note that the string is started using the double quote &#8220;, which means we need to make sure anything in the string that is quoted is either in single quotes or escaped using the backslash. e.g. \&#8221;</li>
    <li>&lt;% versus &lt;%=
        <ol>
            <li>So this is a bit more complicated, if you want to use straight Javascript and don&#8217;t want the output on the line we need to use &lt;%. Also, if you use &lt;% you MUST add a semi-colon ; at the end of the JavaScript line and then follow it with the %&gt; to enclose the line of JS.</li>
            <li>&lt;%= is the way we actually      print out the variables to the template. With this tag, DO NOT put a      semi-colon ; at the end of the line or the template will break.</li>
        </ol>
    </li>
</ol>

<br>
<h3>Dynamic Templating With Includes</h3>
<br>

<p>There is one more thing we should look at. Templating is nothing without includes, so how on earth do you create an include with this system. Well, we can use some other magic that would allow us to access template from other templates.</p>
<p>So lets modify the script a bit, and see what we can do.</p>
<code class="language-javascript">
var template2 = "\
                &lt;table cellspacing='0' cellpadding='0' border='1' id='employee'&gt;\
                    &lt;tbody&gt;\
                        &lt;tr&gt;\
                            &lt;td&gt;Name&lt;/td&gt; \
                            &lt;td&gt;Position&lt;/td&gt; \
                            &lt;td&gt;Pay&lt;/td&gt; \
                            &lt;td&gt;Hours&lt;/td&gt; \
                            &lt;td&gt;Type&lt;/td&gt; \
                            &lt;td&gt;Total Compensation&lt;/td&gt; \
                        &lt;/tr&gt; \
                        <% for (var index = 0; index < employeeList.length; index++){ %>\
                            <% var employee = employeeList[index]; %>\
                            <% var compensation = employee.hours * employee.pay; %>\
                            &lt;tr&gt;\
                                &lt;td&gt;&lt;%= Label.getHTML({ name : employee.name }) %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= employee.position %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= employee.pay %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= employee.hours %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= employee.type %&gt;&lt;/td&gt; \
                                &lt;td&gt;&lt;%= compensation %&gt;&lt;/td&gt; \
                            &lt;/tr&gt; \
                        &lt;% } %&gt;\
                    &lt;/tbody&gt; \
                &lt;/table&gt; \
                ";
var Label = new function() {
    var template = "<strong><%= name %></strong>";
    this.getHTML = function(data) {
        return _.template(template, data);
    };
};
$(document).ready(function() {
    var output = _.template(template2, { employeeList : employeeList } );
    $("#employee2").html(output);
});
</code>
<br>
<p>The corresponding output is below:</p>
<div id="employee2"></div>

<p><br/><br />
Overall with this method of templates and includes we can make very complex sites with a clear separation of data and views.</p>
<p>
<script type="text/javascript" src="/js/template-demo.js"></script>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/01/underscore-js-templates/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Underscore.js</title>
		<link>http://scriptble.com/2011/01/why-underscore-js/</link>
		<comments>http://scriptble.com/2011/01/why-underscore-js/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 00:00:52 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Underscore.JS]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=46</guid>
		<description><![CDATA[Coming from a more technical backend role, and moving into JavaScript many people tend to look for very common functions to make their life easier. However, since JavaScript is considered a "functional" programming language, most of those little conveniences are currently unsupported. So I went searching a bit. Turns out there is a nice little [...]]]></description>
			<content:encoded><![CDATA[<p>Coming from a more technical backend role, and moving into JavaScript many people tend to look for very common functions to make their life easier. However, since JavaScript is considered a "functional" programming language, most of those little conveniences are currently unsupported. So I went searching a bit. Turns out there is a nice little utility belt library that gives us access to all of those built-in methods we all take for granted and are about to be supported in ECMAScript 5.</p>
<p><br/><br />
<br/><br />
As the guys over at Underscore.js put it:</p>
<blockquote><p><a href="http://github.com/documentcloud/underscore/">Underscore</a> is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in <a href="http://prototypejs.org/api">Prototype.js</a> (or <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">Ruby</a>), but without extending any of the built-in JavaScript objects. It's the tie to go along with <a href="http://docs.jquery.com/">jQuery</a>'s tux.</p></blockquote>
<p>Underscore.js uses the built in functions if they exist, and if they don't falls back to its own version. Since there are only a few browsers that currently support ECMAScript 5, it allows us to use these functions even on older browsers.  Now, not only can we start using those constructs before they are officially supported in the browsers, but as soon as they become available underscore.js will get out of the way.</p>
<p><span id="more-46"></span></p>
<p>Here is the current list of who supports ECMAScript 5 and which calls are supported: <a href="http://kangax.github.com/es5-compat-table/">http://kangax.github.com/es5-compat-table/</a> At the time of this writing it looks like underscore wouldn't even be needed in IE9, FF4, Chrome 7,8,9 and is only partialy needed in Opera 10.5-11.</p>
<p>Another key point about underscore.js is they do <strong>NOT</strong> extend any of the built in JavaScript objects. That means, all your existing objects will continue to work as expected. You won't have to worry about underscore.js adding methods to some of your current objects:</p>
<p><code class="language-javascript"><br />
var someArray = [1, 2, 3];</p>
<p>for (var i in someArray){<br />
//do something to someArray[i]<br />
}<br />
</code></p>
<p>We don't need to worry that someArray will now contain a new function that would be returned in the loop. Couple that with all of the new features we can now use, and this looks like a win/win for Frontend Engineers.</p>
<p>Lets take a look at some of the things we get with the library:</p>
<blockquote><p><a href="http://documentcloud.github.com/underscore/#styles">Object-Oriented and Functional Styles</a></p>
<p>Collections</p>
<p><a href="http://documentcloud.github.com/underscore/#each">each</a>, <a href="http://documentcloud.github.com/underscore/#map">map</a>, <a href="http://documentcloud.github.com/underscore/#reduce">reduce</a>, <a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight</a>, <a href="http://documentcloud.github.com/underscore/#detect">detect</a>, <a href="http://documentcloud.github.com/underscore/#select">select</a>, <a href="http://documentcloud.github.com/underscore/#reject">reject</a>, <a href="http://documentcloud.github.com/underscore/#all">all</a>, <a href="http://documentcloud.github.com/underscore/#any">any</a>, <a href="http://documentcloud.github.com/underscore/#include">include</a>, <a href="http://documentcloud.github.com/underscore/#invoke">invoke</a>, <a href="http://documentcloud.github.com/underscore/#pluck">pluck</a>, <a href="http://documentcloud.github.com/underscore/#max">max</a>, <a href="http://documentcloud.github.com/underscore/#min">min</a>, <a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a>, <a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a>, <a href="http://documentcloud.github.com/underscore/#toArray">toArray</a>, <a href="http://documentcloud.github.com/underscore/#size">size</a></p>
<p>Arrays</p>
<p><a href="http://documentcloud.github.com/underscore/#first">first</a>, <a href="http://documentcloud.github.com/underscore/#rest">rest</a>, <a href="http://documentcloud.github.com/underscore/#last">last</a>, <a href="http://documentcloud.github.com/underscore/#compact">compact</a>, <a href="http://documentcloud.github.com/underscore/#flatten">flatten</a>, <a href="http://documentcloud.github.com/underscore/#without">without</a>, <a href="http://documentcloud.github.com/underscore/#uniq">uniq</a>, <a href="http://documentcloud.github.com/underscore/#intersect">intersect</a>, <a href="http://documentcloud.github.com/underscore/#zip">zip</a>, <a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a>, <a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a>, <a href="http://documentcloud.github.com/underscore/#range">range</a></p>
<p>Functions</p>
<p><a href="http://documentcloud.github.com/underscore/#bind">bind</a>, <a href="http://documentcloud.github.com/underscore/#bindAll">bindAll</a>, <a href="http://documentcloud.github.com/underscore/#memoize">memoize</a>, <a href="http://documentcloud.github.com/underscore/#delay">delay</a>, <a href="http://documentcloud.github.com/underscore/#defer">defer</a>, <a href="http://documentcloud.github.com/underscore/#throttle">throttle</a>, <a href="http://documentcloud.github.com/underscore/#debounce">debounce</a>, <a href="http://documentcloud.github.com/underscore/#wrap">wrap</a>, <a href="http://documentcloud.github.com/underscore/#compose">compose</a></p>
<p>Objects</p>
<p><a href="http://documentcloud.github.com/underscore/#keys">keys</a>, <a href="http://documentcloud.github.com/underscore/#values">values</a>, <a href="http://documentcloud.github.com/underscore/#functions">functions</a>, <a href="http://documentcloud.github.com/underscore/#extend">extend</a>, <a href="http://documentcloud.github.com/underscore/#clone">clone</a>, <a href="http://documentcloud.github.com/underscore/#tap">tap</a>, <a href="http://documentcloud.github.com/underscore/#isEqual">isEqual</a>, <a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a>, <a href="http://documentcloud.github.com/underscore/#isElement">isElement</a>, <a href="http://documentcloud.github.com/underscore/#isArray">isArray</a>, <a href="http://documentcloud.github.com/underscore/#isArguments">isArguments</a>, <a href="http://documentcloud.github.com/underscore/#isFunction">isFunction</a>, <a href="http://documentcloud.github.com/underscore/#isString">isString</a>, <a href="http://documentcloud.github.com/underscore/#isNumber">isNumber</a>, <a href="http://documentcloud.github.com/underscore/#isBoolean">isBoolean</a>, <a href="http://documentcloud.github.com/underscore/#isDate">isDate</a>, <a href="http://documentcloud.github.com/underscore/#isRegExp">isRegExp</a> <a href="http://documentcloud.github.com/underscore/#isNaN">isNaN</a>, <a href="http://documentcloud.github.com/underscore/#isNull">isNull</a>, <a href="http://documentcloud.github.com/underscore/#isUndefined">isUndefined</a></p>
<p>Utility</p>
<p><a href="http://documentcloud.github.com/underscore/#noConflict">noConflict</a>, <a href="http://documentcloud.github.com/underscore/#identity">identity</a>, <a href="http://documentcloud.github.com/underscore/#times">times</a>, <a href="http://documentcloud.github.com/underscore/#mixin">mixin</a>, <a href="http://documentcloud.github.com/underscore/#uniqueId">uniqueId</a>, <a href="http://documentcloud.github.com/underscore/#template">template</a></p>
<p>Chaining</p>
<p><a href="http://documentcloud.github.com/underscore/#chain">chain</a>, <a href="http://documentcloud.github.com/underscore/#value">value</a></p>
<p>Pasted from &lt;<a href="http://documentcloud.github.com/underscore/">http://documentcloud.github.com/underscore/</a>&gt;</p></blockquote>
<p>There are a couple of things I want to quickly look at. First, how are they making sure that we use the built-in method if it exists, and second… does that say template?</p>
<p>So Lets take a quick look at the _.each() function to see how they use built-in functions if they exist.</p>
<p><code class="language-javascript"><br />
// The cornerstone, an `each` implementation, aka `forEach`.<br />
// Handles objects implementing `forEach`, arrays, and raw objects.<br />
// Delegates to **ECMAScript 5**'s native `forEach` if available.<br />
var each = _.each = _.forEach = function(obj, iterator, context) {<br />
    var value;<br />
    if (obj == null) return;<br />
    if (nativeForEach &#038;& obj.forEach === nativeForEach) {<br />
        obj.forEach(iterator, context);<br />
    } else if (_.isNumber(obj.length)) {<br />
        for (var i = 0, l = obj.length; i < l; i++) {<br />
            if (iterator.call(context, obj[i], i, obj) === breaker) return;<br />
        }<br />
    } else {<br />
        for (var key in obj) {<br />
            if (hasOwnProperty.call(obj, key)) {<br />
                if (iterator.call(context, obj[key], key, obj) === breaker) return;<br />
            }<br />
        }<br />
    }<br />
};<br />
</code></p>
<p>So if we look a bit more into what they are doing, it looks like they check to see if the object has a function called .forEach(); if it does, use the built-in function, otherwise figure out if it’s an array or object.</p>
<p>As for the second item in this list. I am going to devote <a href="/2011/01/underscore-js-templates/">another post just to templates</a>, how we can use them and make them a bigger part of our frontend projects.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/01/why-underscore-js/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Finding an Element outside of your current iframe</title>
		<link>http://scriptble.com/2011/01/finding-an-element-outside-of-your-current-iframe/</link>
		<comments>http://scriptble.com/2011/01/finding-an-element-outside-of-your-current-iframe/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 19:37:20 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=25</guid>
		<description><![CDATA[Sometimes you are working within an iframe and need to be able to check for an element outside of that frame. It sounds simple enough, and you are right. The following bit of code grabs an element outside of your current iframe: if (typeof window.parent != "undefined"){ window.parent.document.getElementById("SOMEID"); } Pretty simple! Now, lets look at [...]]]></description>
			<content:encoded><![CDATA[Sometimes you are working within an iframe and need to be able to check for an element outside of that frame. It sounds simple enough, and you are right. The following bit of code grabs an element outside of your current iframe:

<code class="language-javascript">
    if (typeof window.parent != "undefined"){
         window.parent.document.getElementById("SOMEID");
    }
</code>

Pretty simple!

Now, lets look at a use case where you might actually need to do something like this. We will use jQuery to grab all of the links outside of the iframe and set an onclick event that will stop the link from working:

<code class="language-javascript">
     $("A", window.parent.document).click(function(e, data) {
           // "this" is now the A that was clicked
           console.log($(this));
           e.preventDefault();
      });
</code>

<span id="more-25"></span>

Now, we couple that with some jQuery UI magic and we can create a nice modal dialog box to pop up when a user clicks and prompt them to make sure they want to navigate away from the current page.

<code class="language-javascript">
     $("A", window.parent.document).click(function(e, data) {
            // prevent the link from redirecting the page
            e.preventDefault();

            // "this" is now the A that was clicked
            var url = $(this).attr('href');

            // create a modal dialog box to prompt the user from leaving the page
            var dom = '&lt;div&gt;&lt;a href="javascript:void(0);" class="leave"&gt;Leave Page&lt;/a&gt; OR ' +
'&lt;a href="javascript: void(0)" class="stay"&gt;Stay&lt;/a&gt;&lt;/div&gt;';


            var modal = $(dom).dialog({
                  modal: true,
                  resizable: false,
                  draggable: false,
                  closeOnEscape: false,
                  dialogClass: "no-titlebar loading-bar dialog-emphasis",
                  width: width || 250,
                  minHeight: height || 50
            });            

            // setup the actions for each of the links in the modal dialog
            $(".leave", modal).click(function(ev, data){
                        window.parent.location.href = url;
            );

            $(".stay", modal).click(function(ev, data){
                        modal.dialog('close');
            });
      });
</code>

* The dom string is causing issues with the syntax highlighter, which is why its on multiple lines, it should all be on one line.

And there you have it, a modal dialog overlay preventing the page from being unloaded without user consent.]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/01/finding-an-element-outside-of-your-current-iframe/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  scriptble.com/tag/jquery/feed/ ) in 0.70518 seconds, on Feb 5th, 2012 at 6:24 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 5th, 2012 at 7:24 pm UTC -->
