<?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>getiblog &#187; jquery</title>
	<atom:link href="http://blog.getify.com/tag/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.getify.com</link>
	<description>open-source, performance, javascript &#38; ui musings</description>
	<lastBuildDate>Mon, 23 Aug 2010 20:50:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Simulated Chaining in JavaScript</title>
		<link>http://blog.getify.com/2010/02/simulated-chaining-in-javascript/</link>
		<comments>http://blog.getify.com/2010/02/simulated-chaining-in-javascript/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 16:18:04 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[chaining]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[labjs]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=213</guid>
		<description><![CDATA[What I have to talk about here is not going to be earth shattering, but it is a technique that has proved useful in a few different sites and scenarios for me. In fact, I regularly get questions regarding advanced use cases for LABjs (a parallel JavaScript loader), and invariably it comes back to something [...]]]></description>
			<content:encoded><![CDATA[<p>What I have to talk about here is not going to be earth shattering, but it is a technique that has proved useful in a few different sites and scenarios for me. In fact, I regularly get questions regarding advanced use cases for <a href="http://labjs.com">LABjs</a> (a parallel JavaScript loader), and invariably it comes back to something along these lines.</p>
<p>If you already understand object/function call chaining, just <a href="#goodstuff">skip down to the good stuff</a>.</p>
<h2>The chains that bind you</h2>
<p>Just so we&#8217;re all on the same page, &#8220;chaining&#8221; is this wonderful functional property of languages like JavaScript (which treat a function as a first-class citizen). It essentially amounts to making a function call, and the return value from the function is itself either another callable function, or more often, an object that has functions which are directly callable.</p>
<p><a href="http://jquery.com">jQuery</a> is probably the most prevalent use of this concept. Some example jQuery code:</p>
<pre style="background-color:#ddd;">
$("p.neat").<strong>addClass</strong>("ohmy").<strong>show</strong>("slow");
</pre>
<p>In this snippet, <span style="background-color:#ddd;">$(&#8230;)</span> is actually a function call, just like <span style="background-color:#ddd;">foo(&#8230;)</span> or <span style="background-color:#ddd;">doSomethingReallyEvilButDontTellAnyone(&#8230;)</span> (just kidding; only Google would name a function something crazy like that).</p>
<p>The return value from the <span style="background-color:#ddd;">$(&#8230;)</span> call is an object, that has a bunch of properties on it, many of whom are functions. Consider that conceptually an object is returned like this (not actual code):</p>
<pre style="background-color:#ddd;">
function $(...) {
   // do something cool
   return {
      addClass:function(...){...},
      show:function(...){...},
      ...
   };
}
</pre>
<p>So, what happens is that when that object is returned from the function, JavaScript will allow you to immediately <em>de-reference</em> the return value (the object), and using &#8220;.&#8221; (dot notation), access its properties. So <span style="background-color:#ddd;">$(&#8230;).<strong>addClass(&#8230;)</strong></span> makes the first chained call (&#8220;addClass&#8221;) off the return value from <span style="background-color:#ddd;">$(&#8230;)</span>. Then, <span style="background-color:#ddd;">addClass(&#8230;)</span> also returns the same (same kind, not identical) object, and so this second return value can identically be de-referenced and a chained function be called. I like to refer to each chained function call as a &#8220;chain link&#8221;.</p>
<p>This chaining can theoretically go on forever (although for code readability it can be argued that 3 or 4 chain links is probably the most you want to practically do in production code, exceptions aside).</p>
<h2>Why chains?</h2>
<p>Probably the single biggest argument for developing code API&#8217;s that are of this chaining style is to pass context along from one function call to another in an automatic and graceful feeling way. For instance, in jQuery&#8217;s case, the reason for chaining is that internally, there&#8217;s a collection (a fancy array) of objects, and as each chained function is called, internally it loops over the collection of objects and performs tasks (such as expanding/contracting the collection, modifying objects in the collection, etc).</p>
<p>jQuery could work functionally this way and achieve the same effect:</p>
<pre style="background-color:#ddd;">
var collection = $("p.neat");
$.addClass(collection,"ohmy");
$.show(collection,"slow");
</pre>
<p>See how we had to pass in the &#8220;collection&#8221; object/array for every function call? It works, but that code is arguably a little less graceful. And certainly it&#8217;s a little more repetitive.</p>
<p>So, chaining was a way to accomplish the same task (context passing across function calls) but in a prettier, more graceful fashion. Generally, the idea of adjusting the way a set of code works to make it more expressive or pleasant is called adding &#8220;syntactic sugar&#8221;.</p>
<p>To be fair, syntactic sugar is not the only reason why chaining in functional languages is useful. In fact, with LABjs, which also has a similar type of chaining API (although internally operates quite differently from jQuery), the reasons were only partially &#8220;sugar&#8221;; chaining in LABjs&#8217; case actually provides an effective solution to guard against certain types of race conditions. </p>
<p>Because of how JavaScript (single-threaded) works, a chain of function calls is more or less guaranteed to complete fully before any other code comes in and interrupts to execute. This is also <em>probably</em> true of a series of distinct function calls in a single code block, but even more definitely so for a chain of function calls or (as we&#8217;ll see in a moment), a loop of function calls.</p>
<h2>So why not a chain?</h2>
<p>Since chains are powerful and also tend to lead to more expressive code (unless abused) and also generally <em>less code</em>, you may wonder, why wouldn&#8217;t we always use chains for everything?</p>
<p>The obvious: some function calls are, by their nature, independent and thus do not need to (or should not!) share a context. Also, under certain circumstances, chaining can be less efficient internally, depending on how the context is stored/shared/used.</p>
<p>Let&#8217;s face it: if you really want to write your entire &#8220;program&#8221; on one line with a bunch of obscure/abusive syntactical tricks, just go write some Perl. I kid, I kid.</p>
<p>But beyond those things, one fundamental fact of chaining is that it&#8217;s not &#8220;dynamic&#8221;. Basically, what I mean by this is that you pretty much hard-code at the time of code writing (aka, &#8220;build time&#8221;) how a chain is constructed. You can&#8217;t decide at run time based on environmental conditions that some parts of the chain are conditionally not executed (like by wrapping them in an if-statement, etc). </p>
<p>The ability to do that kind of run-time logic is restricted syntactically to individual statements/function calls, so a chain will be considered an atomic single indivisible unit for those purposes. You could conditionally decide whether to run one of several different chains depending on conditions, but each chain to be chosen would be pre-defined and for the most part immutable.</p>
<p>So, the truth is, chaining provides a syntactically prettier (more expressive) code approach, but it limits us a little bit in terms of coding flexibility.</p>
<h2>I need more concrete</h2>
<p>To illustrate, let&#8217;s revisit jQuery&#8217;s example code from above. Let&#8217;s say instead that what you really want to do is only run the <span style="background-color:#ddd;">addClass(&#8230;)</span> call if some condition is true (like for instance, the user has a valid login session, or whatever). So, you want to basically do conceptually something like this:</p>
<pre style="background-color:#ddd;">
$("p.neat")
<strong>if (userLoggedIn()) {</strong>  .addClass("ohmy")  <strong>}</strong>  // invalid syntax; will not work!
.show("slow");
</pre>
<p>As I mentioned, you could just have two different chains, one with <span style="background-color:#ddd;">addClass(&#8230;)</span> in the chain, one without it, and choose which chain to execute with your if-statement. This leads to more and repetitive code; a bad thing. DRY (don&#8217;t repeat yourself).</p>
<p>And to be honest, you could also model this in a pure jQuery way (only in the chain using various filters), a variety of different ways. For instance, something like this (while ugly) might work:</p>
<pre style="background-color:#ddd;">
$("p.neat")
.filter(function(){
   return isLoggedIn();
})
.addClass("ohmy")
.end() // ends the most recent filtering operation
.show("slow");
</pre>
<p>What I did here was use <span style="background-color:#ddd;">filter(&#8230;)</span> to basically conditionally empty out the internal collection if not logged in (by returning false for all iterations), meaning the <span style="background-color:#ddd;">addClass(&#8230;)</span> call is essentially ignored, and then revert back to my original collection with a <span style="background-color:#ddd;">.end()</span> call before lastly calling <span style="background-color:#ddd;">.show(&#8230;)</span>.</p>
<p>Let me be clear: while you <em>can</em> do it this way, this is by far not the most efficient or code-friendly way to do so. This would be an example of an anti-pattern, where you are abusing jQuery&#8217;s syntax to solve a problem in a way that it should not be solved. It goes contrary to the spirit of jQuery (&#8220;write less, do more&#8221;).</p>
<h2>Other examples?</h2>
<p>Conditional inclusion of &#8220;chain links&#8221; is only one scenario where traditional chaining is kind of limiting. What if you want to be able to piece together different parts of a chain from various different snippets of code across mutliple functions? This may sound strange, but with complex Web 2.0 web applications, this kind of thing is not uncommon. And it flys in the face of the simple syntactic sugar that chaining is supposed to give us.</p>
<p>Nor are these problems limited to jQuery. With LABjs for instance, a chain might look like this:</p>
<pre style="background-color:#ddd;">
$LAB
.script("framework.js")
.script("loggedin.js")
.wait(function(){
  // do something
});
</pre>
<p>Notice there I may want to <em>only</em> load &#8220;loggedin.js&#8221; if the user is, in fact, logged in. Same syntactic problem as above. But LABjs has no conditional &#8220;filters&#8221; that can modify the chain&#8217;s context, so we have less options (which in this case is a good thing!)</p>
<p>Or, what if I have a CMS system (like Wordpress for instance) that, across various functions, files, templates, etc, needs to load up a variety of different files, all based on various different environmental conditions and which templates are active, etc. Could I do individual $LAB chain calls in each location? Yes. But then I lose the ability to sequence the loads (ensure execution order). Also, it&#8217;s less memory efficient to do 8 different chains with 1 script in each, as opposed to one chain with 8 scripts in it.</p>
<p>Or, what if I want to use LABjs in a larger solution for <a href="http://happyworm.com/blog/2010/01/28/a-simple-and-robust-cdn-failover-for-jquery-14-in-one-line/">creating robust fallback for resource loading from CDN locations</a>? I need to conditionally decide during loading/run-time if I need to add more scripts to the &#8220;queue&#8221; because one load failed. Not possible with traditional chaining.<br />
<a name="goodstuff"></a></p>
<h2>Unravel the ball of yarn</h2>
<p>All this leads up to say that chaining is great and expressive and powerful, but it&#8217;s not complete for all our needs. So, we need to get a little more creative in those cases. And this technique is what I&#8217;m going to call &#8220;Simulated Chaining&#8221;.</p>
<p>Recall that at the top of this post, we talked about how chaining works because the <em><strong>return value</strong></em> from a function is either a function itself (and thus can be called directly), or it can be an object that can be de-refenenced and has properties which are functions to be executed.</p>
<p>So, our solution lies in that sentence (emphasis added). The <em><strong>return value</strong></em> from a function can either be used immediately, or it can be stored and used later. This isn&#8217;t anything new; if you&#8217;ve ever called any function in any language, you know it can return a value that you can store in a variable. What might have escaped you until now is that this return value that you store can be a contextually sensitive object that would otherwise have been used immediately in a chaining situation. And the cool part is it can be used later (like the next loop iteration) to pick up where the chain left off.</p>
<p>So, instead of pre-defining a chain in our code/build-time, we can instead programatically (at run-time) build up a &#8220;list&#8221; (an array/queue for instance) of functions to be called, and then &#8220;simulate&#8221; a chain by looping through the list, calling each function, and storing the return value for use in the next iteration.</p>
<p>For instance, the LABjs script code above can be done like this instead:</p>
<pre style="background-color:#ddd;">
var queue = []; // empty array for now
...
queue[queue.length] = "framework.js";
...
if (isLoggedIn()) { queue[queue.length] = "loggedin.js";
...
var $L = $LAB;
for (var i=0, len=queue.length; i&lt;len; i++) {
   $L = $L.script(queue[i]);
}
$L.wait(function(){
   // do something
});
</pre>
<p>I <em>simulated</em> a chain of function calls with an iterative for-loop. (NOTE: this is conceptually very similar to how you might take what would otherwise be a recursive set of function calls and turn it into a non-recrusive, iterative loop instead, like for performance reasons). The key is: store the return value from a function call, and then use that stored value as the object that makes the next call. Plain and simple. And now more powerful as you can build up your chains at run-time in as complex a way as is necessary.</p>
<p>Theoretically, a very similar approach could be taken for the jQuery examples above. However, I&#8217;ll leave that as an exercise for the reader.</p>
<p>Let&#8217;s look at one last slightly more advanced example of how to use simulated chaining with LABjs (which is nearly identical to how I do it on several of my sites):</p>
<pre style="background-color:#ddd;">
var queue = [];
...
if (conditionOne()) {
   queue.push("framework.js",false); // false will create an empty .wait()
}
...
if (conditionTwo()) {
   queue.push("plugin1.js","plugin2.js",function(){
      // initialize plugins
   });
}
...
queue.push("mypage.js");
...
var $L = $LAB;
for (var i=0, len=queue.length; i&lt;len; i++) {
   if (typeof queue[i] === "function") $L = $L.wait(queue[i]);
   else if (queue[i] === false) $L = $L.wait();
   else $L = $L.script(queue[i]);
}
</pre>
<p>I specify a queue array that can have one of three types of entries: a [string] is interpreted as a script to load, a [false] is interpreted as an empty .wait() call, and a [function] is passed to a .wait(&#8230;) call. I can use any manner of complex logic to build up the queue, and then in one for-loop at the bottom of the page, simulate the chain by looping over the queue.</p>
<p>Hopefully this helps clear up some of the mysticism that is chaining and give you some other ways to approach the challenging use cases you may face in your code. Go forth and chain (or loop)!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/02/simulated-chaining-in-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why DOM-ready still sucks</title>
		<link>http://blog.getify.com/2009/11/why-dom-ready-still-sucks/</link>
		<comments>http://blog.getify.com/2009/11/why-dom-ready-still-sucks/#comments</comments>
		<pubDate>Sat, 21 Nov 2009 16:32:44 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[dom-ready]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[loading]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=44</guid>
		<description><![CDATA[For those of you who are familiar with JavaScript libraries, you are probably at least a little bit aware that there is an &#8220;event&#8221; that occurs during the loading of a page which abstractly represents the point in time in which the browser has fully processed the structure (aka, the &#8220;DOM&#8221;) of the HTML document [...]]]></description>
			<content:encoded><![CDATA[<p>For those of you who are familiar with JavaScript libraries, you are probably at least a little bit aware that there is an &#8220;event&#8221; that occurs during the loading of a page which abstractly represents the point in time in which the browser has fully processed the <strong>structure</strong> (aka, the &#8220;DOM&#8221;) of the HTML document being displayed. </p>
<p>This &#8220;event&#8221; is separate from (and ostensibly noticeably earlier than) the more familiar &#8220;onload&#8221; event, whose defined behavior means that all of the page&#8217;s initial resources have fully loaded &#8212; <strong>before</strong> &#8220;onload&#8221;, there is an earlier state at which things (such as images and styles) are still loading, but the basic plan or skeleton of the page is now known and understood and the browser knows what to expect.</p>
<p>This &#8220;event&#8221; is, in some browsers, an actual <em>event</em>, in other browsers it&#8217;s a state which can be passively observed, and in some browsers, it has to be divined by examining the alignment of the stars and taking into account the wind speed and gravitational pull of various heavenly bodies, divided by the&#8230;</p>
<p>You get the point, there&#8217;s an &#8220;event&#8221; that the browsers try (and some do better than others at this attempt) to expose for when the DOM is ready, which I will now conveniently and uncreatively call &#8220;DOM-ready&#8221;.</p>
<h2>So what if the DOM is ready or not?</h2>
<p>Let me make sure that you understand the importance of DOM-ready. In some cases, if you have JavaScript logic that tries to modify the DOM of your page <em>before</em> this DOM-ready event has occured/passed, you can wreak havoc with that browser, and in some cases, cause a fatal error and browser crash. </p>
<p>Think of it this way: if i&#8217;m standing on one foot, precariously balanced, and trying to pull on a sock over my bare foot, and my wife comes along and tugs on the rug I&#8217;m standing on, am I likely to get that sock put on successfully? Am I even likely to stay standing? Probably not.</p>
<p>So, it&#8217;s wise to make sure that you don&#8217;t take any actions which could adversely affect the browser&#8217;s ability to get his sock on, at least if you don&#8217;t want him to fall over. And that&#8217;s why we have the concept of DOM-ready &#8212; to make sure that you don&#8217;t manipulate the DOM too early.</p>
<p>Moreover, the major JS frameworks (for that matter, most of even the minor JS tools out there) all provide ways for you queue up code to be executed at some later time, that time being when the framework is able to detect that the event has occured and that it&#8217;s now safe for your code to go about the business of changing things.</p>
<h2>The frameworks all take care of that mess for me, right?</h2>
<p>Ahh, don&#8217;t we wish that were completely true. If it were, this post would be somewhat pointless, and you&#8217;d instead be enjoying eating a pizza or watching re-runs of Grey&#8217;s Anatomy.</p>
<p>Alas, the world is not that simple. There&#8217;s a little known, but I believe important, problem with the way DOM-ready detection is accomplished by the frameworks in a cross-browser way. I&#8217;m not going to bore you with all the details of just how this detection occurs, but let&#8217;s just say it gets a little hackish in some cases.</p>
<p>For the lion-share of use cases, the DOM-ready detection that the current framework versions employ is acceptable, at least for all the browsers that most of us really care about working correctly. If you&#8217;re still worried about Netscape 3.0 though, you&#8217;re on your own&#8230; good luck!</p>
<p>But, a subtle problem creeps in when you step outside the normal set of uses cases &#8212; those being where you simply include a &lt;script> tag at the top (or bottom, if you&#8217;re really clever) of your HTML document that loads your framework of choice (let&#8217;s say &#8220;jquery.js&#8221; for the purposes of this post). </p>
<p>Let&#8217;s say you have a mashup where you are pulling together multiple websites, and maybe <a href="http://jquery.com">jQuery</a> is not guaranteed to already be present on the page. &#8220;No problem!&#8221; you say, because you know how to load a script file on-demand, so you&#8217;ll just fire off a request to do so, and wait for jQuery to be present before you proceed to make calls against it (and, of course, then use it to change the page!)</p>
<p>Or, let&#8217;s say you have a bookmarklet that people can use to popup some nifty little widget in their page of choice, and again, you want to make sure that jQuery is present for your code to utilize. Again, we&#8217;ll just load jQuery on-the-fly, and we should be good to go, right?</p>
<p>Or even better, let&#8217;s just say you&#8217;ve got a really complex application, which loads different scripts into the page at different times depending on the state of what the user does. Yet again, you may need to fetch jQuery at some point well after the initial page loading occured.</p>
<p>There&#8217;s yet another use-case, which is actually the one that I ran into that caused me to discover this issue several months ago. If your page uses a script loader, such as <a href="http://labjs.com">LABjs</a>, the one I wrote in cooperation with <a href="http://stevesouders.com">Steve Souders</a> (of Yahoo! and Google fame), you have to be aware of how certain scripts, notably the frameworks, do their DOM-ready detection and how this applies when the script is loaded dynamically. </p>
<p>Because script-loaders remove the &#8220;blocking&#8221; nature of script loading that normal &lt;script> tags provide, it is actually quite possible to get into a situation where you load a script, like &#8220;jquery.js&#8221;, but the rest of the page is so well optimized that the DOM-ready event passes before jQuery arrives. You may very well not intend this to occur, but it can, and worse yet, it can happen as a race-condition, where it happens sometimes, and not others.</p>
<p><strong>(&#8230; more &#8230;)</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2009/11/why-dom-ready-still-sucks/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Content Delivery Network via getiblog.2static.it

Served from: blog.getify.com @ 2010-09-07 20:54:02 -->