<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Alex Sexton]]></title>
  <link href="https://alexsexton.com/atom.xml" rel="self"/>
  <link href="https://alexsexton.com/"/>
  <updated>2018-04-22T23:17:19-05:00</updated>
  <id>https://alexsexton.com/</id>
  <author>
    <name><![CDATA[Alex Sexton]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[The 15 Commandments of Front-End Performance]]></title>
    <link href="https://alexsexton.com/blog/2015/02/the-15-commandments-of-front-end-performance/"/>
    <updated>2015-02-09T05:52:42-06:00</updated>
    <id>https://alexsexton.com/blog/2015/02/the-15-commandments-of-front-end-performance</id>
    <content type="html"><![CDATA[<p>This list is the product of many years of experience in the front-end web development field. I
maintain this list as a reminder to myself to always follow best practices, and to not compromise
on performance, even if I&rsquo;m in a time crunch. I read it before I start any project, and share it
with my team at work (sometimes we joke and call them &ldquo;codemandments&rdquo;) so we can all be on the same
page and do our part to keep the web fast.</p>

<p>Feel free to fork this for your own use.</p>

<p><img src="https://alexsexton.com/images/codemandments.jpg" alt="15 Codemandments" /></p>

<h2>The Commandments</h2>

<ul>
<li><p>I will gzip all server responses.</p></li>
<li><p>I will not include any blocking scripts.</p></li>
<li><p>I will use SVGs instead of JPGs, wherever possible.</p></li>
<li><p>I will not include ads, even ones that request users to join groups or lists on Facebook or
Twitter.</p></li>
<li><p>I will debounce scroll events.</p></li>
<li><p>I will not include third party JavaScript libraries just to detect if users are part of my &ldquo;Just
Cool Friends&rdquo; Facebook group, even if it wouldn&rsquo;t take up that much extra load time.</p></li>
<li><p>I will ignore &ldquo;the fold&rdquo; &ndash; no matter what the client says.</p></li>
<li><p>I will resist the urge to use <code>window.alert</code> to inform visitors that there&rsquo;s a Facebook group for
cool friends and if they wanna join it, that&rsquo;s fine, it only takes a few clicks.</p></li>
<li><p>I will not use <code>translate3d</code> as a hack.</p></li>
<li><p>I will not use synchronous XHR to request the list of friends in my Facebook group, and then use
the list in order to check to see if the current visitor is on the list, and then show a
warning to people who aren&rsquo;t in the group that says that they have their priorities &ldquo;messed up&rdquo;
and that &ldquo;jeeze,&rdquo; it&rsquo;s just a stupid group, why can&rsquo;t you just join it.</p></li>
<li><p>I will use a CDN to serve static content (with no cookies!).</p></li>
<li><p>I will not &ldquo;waste bytes&rdquo; in HTML comments to explain that I&rsquo;d really appreciate it if you joined
the Just Cool Friends™ Facebook group. Things haven&rsquo;t really been the same for me since Linda left, and
it&rsquo;s just so easy to join that it&rsquo;s actually a little bit rude that you wouldn&rsquo;t. I don&rsquo;t post
much in there, and I won&rsquo;t even know if you &lsquo;mute&rsquo; the posts from showing up on your feed. But
honestly it&rsquo;s only like one or two posts every day, so it&rsquo;s not like seeing them in your feed
would kill you.</p></li>
<li><p>I mean it&rsquo;s one crummy group that you join and it makes a guy feel better about himself. The
number of people that join goes up and so does my happiness, how does that not make sense? If you have
a problem with me or with something I&rsquo;ve done in the past, you could just bring it up on the group, that&rsquo;s
literally what it&rsquo;s for. Sometimes I just sit around refreshing the group page, waiting as those numbers
tick up. Each number&hellip;</p></li>
<li><p>&hellip; is another dollar in the bank of my emotional stability. I scratch the pixels into my screen: &ldquo;10,000,000&rdquo;.
I count in my sleep: &ldquo;two-hundred-and-six, two-hundred-and-seven&rdquo; &ndash; each time a friend is added
my joy grows, my sadness pales, my existence means that much more. I weep as the numbers hit
double and then triple digits. So many friends. So many lives touched. How can I be this lucky?
How can I be this influential and popular? See Linda?! I&rsquo;m not a &ldquo;loner.&rdquo; I have way more friends
in my group than you ever had! Maybe you&rsquo;re the loner, Linda, or should I call you &ldquo;Lone-da?!&rdquo;
I hope you can find your own group one day. I hope you can be as meaningful and influential to so many people as
I am. And another friend joins. And another friend joins.</p></li>
<li><p>I will minify all of my CSS.</p></li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Monty Hall Rewrite]]></title>
    <link href="https://alexsexton.com/blog/2014/11/the-monty-hall-rewrite/"/>
    <updated>2014-11-10T13:37:01-06:00</updated>
    <id>https://alexsexton.com/blog/2014/11/the-monty-hall-rewrite</id>
    <content type="html"><![CDATA[<blockquote><p>Here at Acme, Inc. we switched to Soy Milk when we rewrote our app, and now it&rsquo;s 8.3x better than
our old Almond Milk app!</p></blockquote>

<p>I call this a <strong>Monty Hall Rewrite</strong>.</p>

<h2>What&rsquo;s a Monty Hall?</h2>

<p>For those loyal readers who haven&rsquo;t heard of <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem">The Monty Hall Problem</a>,
to which I&rsquo;m alluding, it comes from an old game show, called <em>Let&rsquo;s Make A Deal</em>. It later became
an interesting probability question, and even later a less interesting common interview question.</p>

<p>On <em>Let&rsquo;s Make A Deal</em> (on which Monty Hall was the original host), contestants were shown three
doors and told that behind one of the doors was a brand new car. If they could correctly guess which
door hid the car, they could keep it. The guessing happened in two phases.</p>

<p><img src="https://alexsexton.com/images/montyhall/montyhall.jpg" alt="monty hall problem" style="float:left; margin: 0 20px 20px 0" /></p>

<p>First the contestant would choose a door that they believed had the car behind it. Then one of
Monty Hall&rsquo;s assistants would walk over to the other two doors (the ones that had not
been chosen) and proceed to open one of them, always revealing a bad prize (often a donkey!). Then
the contestant, who now had this <em>new</em> information, was allowed to stick with their original answer
<em>or</em> they could switch to the remaining closed door. That would be the final allowed guess.</p>

<p>They&rsquo;d open the final chosen door and their winnings (hopefully a car!) would be displayed.</p>

<p>In 1990, well into the show, advice columnist <em>Ask Marilyn</em> from Parade Magazine was asked
whether there was a particular advantage to staying or switching. Much to many folks&#8217; surprise at the
time, she answered that the probability of winning was greater if you switched. Thousands of people
wrote in to tell her that she was wrong, but most (not all!) were eventually convinced.</p>

<p>My best summarization would be that, initially, each door has 1/3 probability of being correct.
Therefore, the door that the contestant first chooses has a 1/3 chance of being correct, and the
sum of other 2 choices must be 2/3. When the assistant reveals the donkey behind one of the
remaining doors, it does not change these facts. The original choice still has a 1/3 chance of being
correct, and the sum of the other doors still has a 2/3 chance of being correct. However, now that
the contestant knows that one of the non-chosen doors is a bad door, the 2/3 chance must lie solely
in the unchosen, unopened door.</p>

<p>The conclusion is that you have a 2/3 chance of guessing correctly if you switch, and you have a 1/3
chance of being correct if you stay. This has since been mostly proven as well as observed in repeated
computer simulated trials. It&rsquo;s a bad interview question, but remains a popular Probability 101
problem and a decent anecdote.</p>

<h2>How is this related to rewrites?</h2>

<p>It&rsquo;s not really, obviously. I don&rsquo;t think this metaphor goes very deep, but what it hopefully
gets across is that in the case of a rewrite, the new framework that you choose doesn&rsquo;t
<em>necessarily</em> have more merit than your original choice. <em>The switch itself</em> is what&rsquo;s important.</p>

<p>To immediately break down my own metaphor, the switch doesn&rsquo;t matter as much as the <em>rewrite</em> itself,
but people don&rsquo;t tend to rewrite things on their old stacks.</p>

<p>If you had started with B, and rewrote in A, you&rsquo;d also likely have better results than in your
first pass.</p>

<p>The only fair comparison is a rewrite of your app with your original tools <em>as well as</em>  a rewrite of
your app with the new tools. This isn&rsquo;t very practical, and I&rsquo;m not advocating it. I&rsquo;m simply advocating
awareness of the fallacy.</p>

<p>I&rsquo;d like us all to be keenly aware of what it really takes to make great
software, and to me that involves avoiding false traps. The sexiness of switching to a new, hip library
often comes along with a strong confirmation bias, and an even stronger sunk-cost bias. Let us measure
only what we are able to measure and leave the rest to the marketing teams and social media experts.</p>

<h3>Real Quick For Car People</h3>

<p><img src="https://alexsexton.com/images/montyhall/1989mercedes.jpg" alt="1989 Mercedes C Class" style="float:left;margin-right:20px;margin-bottom:20px;" /></p>

<blockquote><p>&ldquo;This 2015 Hyundai Sonata is way better than our old 1989 Mercedes C Class.&rdquo;</p></blockquote>

<p>Please ignore the 2015 Mercedes C Class.</p>

<br style="clear:both;margin:10px 0;">


<h2>Switching, Rewriting, &amp; Refactoring</h2>

<p>Throw away any assumptions or knowledge of tools that you have and <em>purely</em> consider that if you are switching,
rewriting, or refactoring, you are now <code>n years</code> better at programming than you were when you
initially wrote the software.</p>

<p>Now factor in that you&rsquo;ve had <code>x years</code> more time to consider the <em>exact</em> problem that you&rsquo;re trying to
solve as well as rid yourself of uninformed assumptions. When going in for the rewrite, you have a much
clearer picture of what a successful product looks like, purely <em>because</em> of the initial app. You
know to abstract certain parts of the code that need to grow, and to externalize other parts that you
know you won&rsquo;t be able to support indefinitely. For all its negative qualities, <a href="http://en.wikipedia.org/wiki/Second-system_effect">second system
syndrome</a> is actually somewhat helpful in understanding
exactly what needs to be built (even though there isn&rsquo;t time to build it all).</p>

<p>In your original app, things almost certainly went directions that you weren&rsquo;t expecting. You had
to tack on widgets and endpoints that you never intended, and you ended up with some frankenversion
of your original vision. The rewrite allows you to consider all of this stuff from the begining (at
least for a bit), which results in things being &lsquo;faster&rsquo; or &lsquo;more secure&rsquo; or &lsquo;more user friendly&rsquo; or
whatever metric your new app is better than the old one.</p>

<p>If you&rsquo;d like another bad metaphor, imagine your original app as <a href="http://simpsons.wikia.com/wiki/The_Homer">The Homer</a>.</p>

<h2>Are you talking about any specific rewrite? (aka are you sub-blogging me?)</h2>

<p>No. This seems to come up a lot, though. I&rsquo;m happy to tell you that I think you&rsquo;re measuring things
incorrectly directly to your face. If you must have an example, I&rsquo;d say that Facebook&rsquo;s switch from
an HTML5 app to a native app would be an ideal candidate for a well-defined Monty Hall Rewrite.</p>

<p>If you weren&rsquo;t familiar, their old, not-so-great app was written as an HTML5 web app in a native wrapper. It
had all sorts of warts (HTML as the data transfer layer, etc) and was indeed not that nice. Mark
Zuckerberg famously said that <a href="http://techcrunch.com/2012/09/11/mark-zuckerberg-our-biggest-mistake-with-mobile-was-betting-too-much-on-html5/">betting on HTML5 was one of their worst mistakes</a> and that
the new native app was better, faster, stronger.</p>

<p>So after they had a laundry list of things they didn&rsquo;t like about their old app, they set out to
completely rewrite a new app with new tools. It was better! And faster! But I think it is wrong to attribute a vast
majority of these improvements to the fact they were now &ldquo;native,&rdquo; but instead to the fact that they were <em>rewritten</em>.</p>

<p>Luckily, at the time, Sencha put out something called <a href="http://vimeo.com/55486684">Fastbook</a>. A Facebook
&ldquo;rewrite&rdquo; of sorts to match the new native Facebook app. They made a nice video about how they were
able to make a faster/snappier/cooler
app than the new native one, all in HTML5 (with Sencha&rsquo;s tooling, obviously). I don&rsquo;t necessarily
think Facebook should have switched to the Sencha platform or anything along those lines, but it is
a good example of people blaming their tools for causing their old problems, and thanking their new
tools for solving them.</p>

<p>To Facebook&rsquo;s credit, <a href="https://twitter.com/tobie">@tobie</a> eventually put out
<a href="http://lists.w3.org/Archives/Public/public-coremob/2012Sep/0021.html">a list of things he&rsquo;d wish the web would fix</a>
with things that had actively been a problem for them when building those old web-based apps. I haven&rsquo;t seen the
equivalent list on the problems building cross platform native apps, but the list was quite valid.
It&rsquo;s much more in line with the type of discourse we <em>should</em> be having when we make claims about
why our new choices are better than our old ones.</p>

<h2>What now?</h2>

<p>I don&rsquo;t mean to discourage rewrites, trying new tools, or any other variant on that theme. I <em>love</em>
a good rewrite, and I&rsquo;m constantly trying new tools. More than anything I wanted to point a thing
out that I think muddies a lot of the waters when developers are evaluating new tools.</p>

<p>So when you pick new tools, don&rsquo;t trash your old ones. And once you decide on one tool instead of another
that does something very similar, don&rsquo;t speak as if you made the <em>obvious</em> or <em>correct</em> choice.
Instead, focus on the fact that you made a <em>good</em> choice.</p>

<p>Software is not a zero-sum game. Two tools can be good at the same time, and we all win because of it.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Productivity Cycle]]></title>
    <link href="https://alexsexton.com/blog/2014/1/the-productivity-cycle/"/>
    <updated>2014-01-15T13:05:00-06:00</updated>
    <id>https://alexsexton.com/blog/2014/1/the-productivity-cycle</id>
    <content type="html"><![CDATA[<p>People are interesting. We know so little about ourselves compared to what we&rsquo;d like to think we know. We&rsquo;re all subtly different even though we&rsquo;re, on a whole, overwhelmingly predictable. There are copious studies to back up &ldquo;average&rdquo; data from people, and plenty of arm-chair anthropologists and psychologists that have very nice theories on how we tick. But most of us aren&rsquo;t &lsquo;average,&rsquo; and perhaps some of us <em>tock</em> more than we <em>tick</em> (mark this as the first of many &ldquo;stretches&rdquo; in this post).</p>

<p>I&rsquo;d like to take the chance, while we&rsquo;re still mostly clueless, to write some of my non-scientific theories on cognitive ability and &ldquo;focus&rdquo; (the noun) in the context of creating and building things (or &ldquo;shipping,&rdquo; as it were).</p>

<h2>Motive and Privilege</h2>

<p>I see a thin thread woven through everything that I do, and everything that I see my peers do.</p>

<p><strong>Legacy.</strong></p>

<p>We&rsquo;re all creative, and many of us want to &ldquo;build things.&rdquo; I hear it often in interviews, and over beers, that it&rsquo;s just built into the core of many of us to want to &ldquo;create something from nothing.&rdquo; It often takes shape as some other pleasant-sounding turn of phrase, but the &ldquo;need to create&rdquo; seems to be innate in all but the most blissful of us. In my experience, this can often be traced back to the desire for someone to &lsquo;make their mark,&rsquo; or as I previously alluded, the desire to pursue a legacy.</p>

<p>I&rsquo;m all for this. This feeling is built in to my DNA as well. And while I would hope to have purely selfless reasons for wanting to create things, I&rsquo;m certain that my ego, and my human-nature drive me to want to live longer than my bones.</p>

<p>I can&rsquo;t help but lead with &ldquo;ego&rdquo; and &ldquo;legacy&rdquo; because the entire ability to create something from nothing (programming) and to get disproportionally rewarded for doing so (programming salaries) comes along with more than a touch of blind privilege. It&rsquo;s a pretty good spot to be in to be hacking your mental focus levels so you can build bigger and better websites. Blindness to our privilege is mostly to be expected as long as we fight to improve our own awareness and adjust our actions appropriately. Read on now, forewarned of my ego, blindness to privilege, and extreme lack of brevity.</p>

<h2>Caffeine is a Zero-Sum Game</h2>

<p><img src="https://alexsexton.com/images/prod_cycle/focuswave.png" alt="/images/prod_cycle/focuswave.png" /></p>

<p><small>Ostensibly, this is a graph of my potential &ldquo;focus&rdquo; levels during a day.</small></p>

<p>I read a <em>fascinating</em> blog post several years ago by <a href="http://randomwalker.info/">Arvind Narayanan</a> called <a href="http://arvindn.livejournal.com/57651.html">The Calculus of Caffeine Consumption</a>. It was pretty eye-opening for me to see my &ldquo;focus&rdquo; levels throughout the day graphed out as a sine wave. Naturally, it&rsquo;s a massive over-simplification, but in my personal experience, not an entirely incorrect approximation of my energy levels in a day. I am tired, perk up, get hungry and eat and dip down, then hit a stride, rinse and repeat. It&rsquo;s not a sine wave, but it&rsquo;s a wave alright.</p>

<p>Like my Uncle Ray always says, <em>&ldquo;Any wave is sinusoidal with a sufficiently low sampling rate!&rdquo;</em>, though I think eventually it becomes a straight line. (Which I guess is a wave with an amplitude of zero?)</p>

<p>Our wave of &ldquo;focus&rdquo;/energy has all the normal properties of a wave: a wavelength, a period, and an amplitude. The premise of the article is that caffeine, a stimulant, is often consumed during the low points in our day. So we drink coffee when we wake up or when we feel tired after lunch in order to boost our ability to concentrate and sometimes even function. The effect of this decision that is lost on us, is that <em>this reduces the total amplitude of our &ldquo;focus&rdquo; wave</em>.</p>

<p>In other words, <strong>by consuming caffeine to reduce how low we get during the low points, we inherently reduce our high points as well.</strong></p>

<p>Narayanan states that this type of consumption actually works pretty well for people who are trying keep from falling below a threshold of &ldquo;focus&rdquo; or energy. Consider a construction worker, data-entry employee, truck-driver, or similar, where the time put into the task is important, and dipping below a certain level of energy would be dangerous/deadly.</p>

<p>Creative workers, however, don&rsquo;t have the same limitations. They often need &ldquo;a moment of clarity&rdquo; to spark their work, or to break out of &ldquo;writer&rsquo;s block.&rdquo; They would want the absolute highest amplitude of focus, regardless of the consequences on the downside, and to be working while at their highs.</p>

<p>Narayanan, a true hacker spirit (read: CS Ph.D. and Assistant Professor at Princeton), attempts to exploit this relationship to his advantage. Could he use caffeine to increase the amplitude of his &ldquo;focus?&rdquo; A conclusive answer here would take quite a few more double blind studies, but in my experience, and seemingly in Dr. Narayanan&rsquo;s as well, the answer is a resounding <strong>&ldquo;yes.&rdquo;</strong></p>

<p><em>Drink a latte 30 minutes before a high point, work as hard as you can, and then use the warmth of your laptop to take a nap a few hours later, because you&rsquo;ll be spent.</em></p>

<p>Caffeine is a zero-sum game, but you can use that to your advantage. Consuming caffeine in time for it to affect you at the exact peak of your &ldquo;focus wave&rdquo; effectively makes the highs higher, and the lows lower. The rich get richer, while the poor get poorer. It&rsquo;s like the sad state of our socioeconomic classes, except not awful, and for brain power!</p>

<h2>You Require More Vespene Gas</h2>

<p>Many people who have read Daniel Kahneman&rsquo;s <a href="http://www.amazon.com/Thinking-Fast-Slow-Daniel-Kahneman/dp/0374533555"><em>Thinking Fast And Slow</em></a> will remember the <a href="http://books.google.com/books?id=TA7Q27RWlj0C&amp;lpg=PT62&amp;ots=qSRd7MEIpZ&amp;pg=PT62#v=onepage&amp;q&amp;f=false">chocolate cake experiment</a>.</p>

<p><img src="https://alexsexton.com/images/prod_cycle/cake.jpg" alt="/images/prod_cycle/cake.jpg" /></p>

<p><small>Photo by <a href="http://www.flickr.com/photos/foodthinkers/">Food Thinkers</a> under <a href="http://creativecommons.org/licenses/by-nc-sa/2.0/">CC-by-NC-SA</a></small></p>

<p>The experiment, led by Baba Shiv at Stanford University, is pretty simple. Half the students are asked to remember a 2 digit number, and half are asked to remember a 7-digit number. They walk down a hall, are told they&rsquo;re done, and are asked if they want chocolate cake, or fruit salad as a refreshment. The students who were asked to remember the 7-digit number were nearly twice as likely to choose the chocolate cake. Why is this?</p>

<p>Simply put, we have a finite amount of mental energy. The students who spent their energy on remembering 7-digit numbers had no more energy left to spend on avoiding cake.</p>

<p>The prefrontal cortex is primarily responsible for the things that creative people crave, like focus, but also other functions like short-term memory, abstract problem solving, and willpower. The conclusion of the chocolate cake experiment implies that there is a finite amount of resources in the prefrontal cortex, and that one system&rsquo;s use of those resources could directly affect the available resources of another function.</p>

<p><img style="float:left;margin:0 30px 0 0" src="https://alexsexton.com/images/prod_cycle/wavearea.jpg" alt="Graph with area under curve highlighted"> In the context of our sine-wave, I&rsquo;m pretty sure I could make a good reference to calculus, because this concept has a lot to do with the area under the curve, but I&rsquo;ll get it wrong, and I won&rsquo;t hear the end of it in the comments.</p>

<p>This plays into our first theory quite well. If we use more mental energy in a quick burst (because we have a higher amplitude), we&rsquo;ll need deeper rest in order to recharge this energy. During our rest periods, the troughs in our sine-wave, we have to refill the energy that we spent during our peaks.</p>

<p>I can&rsquo;t safely postulate much about how to best do this, except for that studies show that naps are increasingly good for doing such things. Since you&rsquo;re probably not going to have your big break during a lull in your cognitive ability, why not speed up the process of getting to another high point? Nap away! Refuel the exact part of your brain that will allow you to get in the zone again.</p>

<p>Some folks will recommend a <a href="http://en.wikipedia.org/wiki/Power_nap#The_caffeine_nap">caffeine nap</a>. I don&rsquo;t have a ton of <em>intentional</em> experience with caffeine naps, but the idea is that if you consume caffeine just prior to taking a nap, you&rsquo;ll sleep until it kicks in (usually takes at least 30min for caffeine to metabolize), and then it&rsquo;ll allow you to skip some of the groggier<em>[1]</em> steps on your way back to productivity. It probably works.</p>

<p><small><em>[1]</em> Apparently, I can&rsquo;t write the word &lsquo;grog&rsquo; without thinking about Guybrush Threepwood.</small></p>

<h3>Moderation</h3>

<p>I would add, finally, that Dr. Narayanan found that the body adjusts to regular caffeine intake in as little as 2 to 3 weeks. That means that if you&rsquo;re a long-time coffee-drinker, you <em>really do</em> need that cup of coffee to get going in the morning in order to get up to your pre-caffeine addiction baseline.</p>

<p>He notes that it takes 5 days to reach adenosine normality (good) if you&rsquo;re not consuming caffeine. He retrospectively adds that he initially did not place enough value in these &lsquo;quitting cycles&rsquo; (hinting that perhaps you should not repeat his mistakes).</p>

<h2>Practical Application</h2>

<p>Most of this should be obvious at this point, so I won&rsquo;t drag on.</p>

<ul>
<li>Plan your high points, work during them</li>
<li>Refuel during low points instead of stretching them out with forced work</li>
<li>Slingshot your amplitude with caffeine; 3 weeks on and 1 week off</li>
<li>Avoid non-intentional caffeine, only drink it on schedule</li>
<li>Don&rsquo;t ignore the people you love</li>
</ul>


<h2>The Nap Month</h2>

<p>I have nothing but my own personal experience to back this up, but I find that my motivation and passion levels work in a similar way on a <strong>yearly</strong> cycle as they do on a <strong>daily</strong> cycle. For parts of the year, I&rsquo;m excited by work, and go out of my way to build things in my free time, and other parts of the year, I just want to come home and binge watch a season of a TV show on Netflix.</p>

<p>For this reason I have to wonder if some of the same energy principles apply. <strong>Can I increase the intensity and duration of the productive months?</strong> If so, at what cost?</p>

<p>I really struggle (in a not very serious kind of way) during the month or two when I feel like I can&rsquo;t get anything done, but I think we can use a similar trick to help our productivity pick up again. Specifically, we need to A) simulate caffeine on a macro scale, and B) simulate naps on a macro scale.</p>

<h3>Macrocaffeine</h3>

<p>I find that an interesting, new passion project gets my creative energy flowing much better than jumping into old work. If I really want to get in the mood to program, I&rsquo;ll hop off my projects with deadlines and build something that I know probably won&rsquo;t ever even get finished, but that I&rsquo;m just excited to build.</p>

<p>Caffeine blocks adenosine (a sleep chemical) receptors in our brain, causing us to avoid sleep longer. If we substitute the current list of things we have to do, with a temporarily more engaging list, it may give us the same slingshot effect that caffeine does for our energy on a micro level.</p>

<h3>Macronaps</h3>

<p>This one seems a little bit more straight forward to me.</p>

<p><strong>Just stop working so much.</strong></p>

<p>Take a nap from your work. I understand that this is not a viable solution for businesses that intend to make money, but I think there can be some good compromises here. Namely, most hip tech companies have very generous vacation allowances already. Use your vacation during a low point, and in perfect cliché form, &ldquo;recharge.&rdquo;</p>

<p>Additionally, companies with large enough teams can have two modes of employment that employees could ideally opt into. &ldquo;Passion-mode&rdquo; and &ldquo;coast-mode.&rdquo; Someone who is on an upswing should get put on a big project that&rsquo;s going to take a lot of energy. Someone who is burnt out from the last big project should be given work that will allow them to show up a little late, and leave a little early.</p>

<p>There&rsquo;s lots of work like this. The support team at your company would probably love it if developers frequently did 6-hour customer support stints. In no way do I imply that the support team doesn&rsquo;t regularly break its back working very demanding hours/problems and doesn&rsquo;t deserve their own down-time. There&rsquo;s also plenty of documentation that I&rsquo;m happy to churn out during my down month.</p>

<p>The point is to allow employees to be maximally lazy while still maintaining their minimum required value. The more quickly I&rsquo;m able to get through the less motivated time, the more quickly I&rsquo;ll be able to jump back into a difficult and challenging project and do it well.</p>

<h2>A Final Moment of Clarity</h2>

<p>I have very few projects and accomplishments that haven&rsquo;t come to me in a &ldquo;moment of clarity.&rdquo; Naturally, I want to maximize the amount of these moments, and increase the odds that I&rsquo;ll be working on something that I love when they occur. I have no idea if hacking your body is a good long-term strategy for making this happen, but I find that researching all of this sleep stuff is an excellent tool for procrastinating during my focus droughts.</p>

<p>I can&rsquo;t guarantee that any of this will resonate with you, or work for you if you try it. But I do think that everyone goes through the motivational recessions, and we should be actively attempting to eliminate or reduce them. What is Quantitative Easing for the Soul?</p>

<p>I simply want my hard work to be spent most efficiently.</p>

<p><small>Special thanks to <a href="https://twitter.com/hazelcough">Michelle Bu</a> for reading this ahead of time.</small></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Understanding JavaScript Inheritance]]></title>
    <link href="https://alexsexton.com/blog/2013/04/understanding-javascript-inheritance/"/>
    <updated>2013-04-12T03:33:00-05:00</updated>
    <id>https://alexsexton.com/blog/2013/04/understanding-javascript-inheritance</id>
    <content type="html"><![CDATA[<p>So someone shoulder-taps you and asks you to explain the concepts behind JavaScript Inheritance to them. In my eyes you&rsquo;ve
got a few options.</p>

<h2>The Terminology Play</h2>

<p>You mention that it&rsquo;s <a href="https://www.google.com/search?q=define%3A+prototypal"><strong>prototypal</strong></a> inheritance, not <strong>prototypical</strong>
and pretty much gloss over the rest, comfortable in your superiority in terminology. You may go as far as saying &ldquo;Objects just
come from other Objects because there aren&rsquo;t any classes.&rdquo; Then you just link to
<a href="http://javascript.crockford.com/prototypal.html">Crock&rsquo;s Post</a> on it, and try to seem busy for the next few days.</p>

<p>Many years later you find out that <strong>Prototypal</strong> and <strong>Prototypical</strong> are synonyms, but you choose to ignore this.</p>

<h2>The Like-Classical-Inheritance-But-Different Play aka the Run-On Sentence Play</h2>

<p>&ldquo;So in Java, like, you have classes or whatever, right? Well so imagine that you don&rsquo;t have those, but you still want to do
that same type of thing or whatever, so then you just take another object instead of a class and you just kind of use it
like it&rsquo;s a class, but it&rsquo;s not because it can change and it&rsquo;s just a normal object, and if it changes and you don&rsquo;t override
the object, oh yea, so you can decide to override the parent object class thing, so if you dont do that and the parent changes
the link is live&hellip;&rdquo;</p>

<p>And so forth.</p>

<h2>The Animal Play</h2>

<p>This is a pretty popular one.</p>

<p>So let&rsquo;s say we want to make an <code>Animal</code> class in our code. As is often necessary in production JavaScript applications.</p>

<p>First we make a &ldquo;constructor function,&rdquo; which acts kind of like a constructor method on the inside of a class in a classical
language when it&rsquo;s invoked with the <code>new</code> operator. Except this one is on the outside.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">Animal</span> <span class="p">(</span><span class="nx">name</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">name</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">myAnimal</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Animal</span><span class="p">(</span><span class="s1">&#39;Annie&#39;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then we want to have actions that all animals can do.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">Animal</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">walk</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">+</span> <span class="s1">&#39; is walking.&#39;</span><span class="p">);</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>But then you want to define a more specific <em>type</em> of animal. Things start to get weird.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// I think we need to define a new Animal type and extend from it somehow</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">Dog</span> <span class="p">(</span><span class="nx">name</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">name</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// BUT HOW DO WE EXTEND</span>
</span><span class='line'><span class="c1">// WITHOUT AN INSTANCE TO USE?</span>
</span><span class='line'><span class="nx">Dog</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="nx">Animal</span><span class="p">.</span><span class="nx">prototype</span><span class="p">;</span> <span class="c1">// ?? I HAVE NO IDEA</span>
</span><span class='line'><span class="c1">// Maybe that&#39;ll work for some stuff?</span>
</span><span class='line'><span class="c1">// ProHint™: probably not much, once you start modifying one of them :D</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then you remember that Prototypal Inheritance doesn&rsquo;t really do &lsquo;classes&rsquo; so much. So you do something like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">Dog</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Animal</span><span class="p">(</span><span class="s1">&#39;Annie&#39;</span><span class="p">);</span> <span class="c1">// ??? NO THATS NOT IT &gt;:(</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Maybe we can try Object.create? I hear it&#39;s prototypal-y</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">Dog</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">Animal</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Maybe that worked? Let&#39;s see...</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">myDog</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Dog</span><span class="p">(</span><span class="s1">&#39;Sparky&#39;</span><span class="p">);</span>
</span><span class='line'><span class="c1">// TypeError: object is not a function</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Shucks</span>
</span></code></pre></td></tr></table></div></figure>


<p>And you eventually simply converge on the&hellip;</p>

<h2>The Father/Son Analogy Play</h2>

<p>Here we go. Finally a <strong>real world</strong> example of &lsquo;instances begetting instances.&rsquo; It&rsquo;ll be a perfect analogy.
It&rsquo;s even an interview question some places. Let&rsquo;s see how we might implement the relationship of a father
and son (or a parent to its child) in JavaScript.</p>

<p>We&rsquo;ll start out like we did before, with a Human constructor</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">Human</span><span class="p">(</span> <span class="nx">name</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">name</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then we&rsquo;ll add in a common human shared action.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">Human</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">sayHi</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;Hello, I&#39;m &quot;</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">name</span><span class="p">);</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>So we&rsquo;ll create my dad first.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// Instantiate him</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">myDad</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Human</span><span class="p">(</span><span class="s1">&#39;Bill Sexton&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Greet him</span>
</span><span class='line'><span class="nx">myDad</span><span class="p">.</span><span class="nx">sayHi</span><span class="p">();</span>
</span><span class='line'><span class="c1">// &quot;Hello, I&#39;m Bill Sexton&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p><strong>Score.</strong> Now let&rsquo;s create me.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// Let&#39;s use ES5 `object.create` in order to be as &#39;prototypal&#39; as possible.</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">me</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">myDad</span><span class="p">);</span>
</span><span class='line'><span class="nx">me</span><span class="p">.</span><span class="nx">sayHi</span><span class="p">();</span>
</span><span class='line'><span class="c1">// &quot;Hello, I&#39;m Bill Sexton&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>It&rsquo;s a start! Seems like I inherited a little too much from my dad, but I inherited, none the less.</p>

<p>Let&rsquo;s try to smooth things out to make the analogy work better. So we&rsquo;ll instantiate objects without
a name and have a parent name them after they&rsquo;re created.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// Wrap it all together</span>
</span><span class='line'><span class="kd">function</span> <span class="nx">makeBaby</span><span class="p">(</span><span class="nx">parent</span><span class="p">,</span> <span class="nx">name</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// Instantiate a new object based on the parent</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">baby</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">parent</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Set the name of the baby</span>
</span><span class='line'>  <span class="nx">baby</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">name</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Give the baby away</span>
</span><span class='line'>  <span class="k">return</span> <span class="nx">baby</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Perfect. Now the baby can <code>sayHi</code> on its own.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">alex</span> <span class="o">=</span> <span class="nx">makeBaby</span><span class="p">(</span><span class="nx">myDad</span><span class="p">,</span> <span class="s1">&#39;Alex Sexton&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">alex</span><span class="p">.</span><span class="nx">sayHi</span><span class="p">();</span>
</span><span class='line'><span class="c1">// &quot;Hello, I&#39;m Alex Sexton&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Err. <strong>yipes</strong>. Babies can&rsquo;t talk. And what&rsquo;s this deal with a baby being made by <strong>one</strong> parent. Not to worry,
we can fix all of this.</p>

<p>First we&rsquo;ll probably want to try to take two parents into the <code>makeBaby</code> function (no giggles).</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">makeBaby</span><span class="p">(</span><span class="nx">father</span><span class="p">,</span> <span class="nx">mother</span><span class="p">,</span> <span class="nx">name</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">baby</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(...</span><span class="c1">// fuuu</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Multiple Inheritance! How did <em>you</em> get here? Ugh. Fine. We&rsquo;ll just simply mock the human chromosome pattern into
our little inheritance example.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// Let&#39;s take a set of 4 genes for ease of</span>
</span><span class='line'><span class="c1">// example here. We&#39;ll put them in charge</span>
</span><span class='line'><span class="c1">// a few things.</span>
</span><span class='line'><span class="kd">function</span> <span class="nx">Human</span> <span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="nx">genes_mom</span><span class="p">,</span> <span class="nx">genes_dad</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">name</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Set the genes</span>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">genes</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">darkHair</span><span class="o">:</span> <span class="k">this</span><span class="p">.</span><span class="nx">_selectGenes</span><span class="p">(</span><span class="nx">genes_mom</span><span class="p">.</span><span class="nx">darkHair</span><span class="p">,</span> <span class="nx">genes_dad</span><span class="p">.</span><span class="nx">darkHair</span><span class="p">),</span>
</span><span class='line'>    <span class="nx">smart</span><span class="o">:</span>    <span class="k">this</span><span class="p">.</span><span class="nx">_selectGenes</span><span class="p">(</span><span class="nx">genes_mom</span><span class="p">.</span><span class="nx">smart</span><span class="p">,</span>    <span class="nx">genes_dad</span><span class="p">.</span><span class="nx">smart</span><span class="p">),</span>
</span><span class='line'>    <span class="nx">athletic</span><span class="o">:</span> <span class="k">this</span><span class="p">.</span><span class="nx">_selectGenes</span><span class="p">(</span><span class="nx">genes_mom</span><span class="p">.</span><span class="nx">athletic</span><span class="p">,</span> <span class="nx">genes_dad</span><span class="p">.</span><span class="nx">athletic</span><span class="p">),</span>
</span><span class='line'>    <span class="nx">tall</span><span class="o">:</span>     <span class="k">this</span><span class="p">.</span><span class="nx">_selectGenes</span><span class="p">(</span><span class="nx">genes_mom</span><span class="p">.</span><span class="nx">tall</span><span class="p">,</span>     <span class="nx">genes_dad</span><span class="p">.</span><span class="nx">tall</span><span class="p">)</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Since genes affect you since birth we can set these as actual attributes</span>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">attributes</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">darkHair</span><span class="o">:</span> <span class="o">!!</span><span class="p">(</span><span class="o">~</span><span class="k">this</span><span class="p">.</span><span class="nx">genes</span><span class="p">.</span><span class="nx">darkHair</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">&#39;D&#39;</span><span class="p">)),</span>
</span><span class='line'>    <span class="nx">smart</span><span class="o">:</span> <span class="o">!!</span><span class="p">(</span><span class="o">~</span><span class="k">this</span><span class="p">.</span><span class="nx">genes</span><span class="p">.</span><span class="nx">smart</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">&#39;D&#39;</span><span class="p">)),</span>
</span><span class='line'>    <span class="nx">athletic</span><span class="o">:</span> <span class="o">!!</span><span class="p">(</span><span class="o">~</span><span class="k">this</span><span class="p">.</span><span class="nx">genes</span><span class="p">.</span><span class="nx">athletic</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">&#39;D&#39;</span><span class="p">)),</span>
</span><span class='line'>    <span class="nx">tall</span><span class="o">:</span> <span class="o">!!</span><span class="p">(</span><span class="o">~</span><span class="k">this</span><span class="p">.</span><span class="nx">genes</span><span class="p">.</span><span class="nx">tall</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">&#39;D&#39;</span><span class="p">))</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// You don&#39;t have access to your own gene selection</span>
</span><span class='line'><span class="c1">// so we&#39;ll make this private (but in the javascript way)</span>
</span><span class='line'><span class="nx">Human</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">_selectGenes</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">gene1</span><span class="p">,</span> <span class="nx">gene2</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// Assume that a gene is a 2 length array of the following possibilities</span>
</span><span class='line'>  <span class="c1">// DD, Dr, rD, rr -- the latter being the only non &quot;dominant&quot; result</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Simple random gene selection</span>
</span><span class='line'>  <span class="k">return</span> <span class="p">[</span> <span class="nx">gene1</span><span class="p">[</span><span class="nb">Math</span><span class="p">.</span><span class="nx">random</span><span class="p">()</span> <span class="o">&gt;</span> <span class="mf">0.5</span> <span class="o">?</span> <span class="mi">1</span> <span class="o">:</span> <span class="mi">0</span><span class="p">],</span> <span class="nx">gene2</span><span class="p">[</span><span class="nb">Math</span><span class="p">.</span><span class="nx">random</span><span class="p">()</span> <span class="o">&gt;</span> <span class="mf">0.5</span> <span class="o">?</span> <span class="mi">1</span> <span class="o">:</span> <span class="mi">0</span><span class="p">]</span> <span class="p">]</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="nx">Human</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">sayHi</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;Hello, I&#39;m &quot;</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">name</span><span class="p">);</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">makeBaby</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="nx">mother</span><span class="p">,</span> <span class="nx">father</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// Send in the genes of each parent</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">baby</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Human</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="nx">mother</span><span class="p">.</span><span class="nx">genes</span><span class="p">,</span> <span class="nx">father</span><span class="p">.</span><span class="nx">genes</span><span class="p">);</span>
</span><span class='line'>  <span class="k">return</span> <span class="nx">baby</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p><strong>Elementary</strong>. My only beef is that we no longer are using real prototypal inheritance.
There is no live link between the parents and the child. If there was only one parent,
we could use the <code>__proto__</code> property to set the parent as the prototype after the
baby was instantiated. However we have two parents&hellip;</p>

<p>So we&rsquo;ll need to implement runtime getters that do a lookup for each parent via
<a href="http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies">ES Proxies</a>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">makeBaby</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="nx">mother</span><span class="p">,</span> <span class="nx">father</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// Send in the genes of each parent</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">baby</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Human</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="nx">mother</span><span class="p">.</span><span class="nx">genes</span><span class="p">,</span> <span class="nx">father</span><span class="p">.</span><span class="nx">genes</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Proxy the baby</span>
</span><span class='line'>  <span class="k">return</span> <span class="k">new</span> <span class="nx">Proxy</span><span class="p">(</span><span class="nx">baby</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">get</span><span class="o">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">proxy</span><span class="p">,</span> <span class="nx">prop</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="c1">// shortcut the lookup</span>
</span><span class='line'>      <span class="k">if</span> <span class="p">(</span><span class="nx">baby</span><span class="p">[</span><span class="nx">prop</span><span class="p">])</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="nx">baby</span><span class="p">[</span><span class="nx">prop</span><span class="p">];</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>      <span class="c1">// Default parent</span>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">parent</span> <span class="o">=</span> <span class="nx">father</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>      <span class="c1">// Spice it up</span>
</span><span class='line'>      <span class="k">if</span> <span class="p">(</span><span class="nb">Math</span><span class="p">.</span><span class="nx">random</span><span class="p">()</span> <span class="o">&gt;</span> <span class="mf">0.5</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">parent</span> <span class="o">=</span> <span class="nx">mother</span><span class="p">;</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>      <span class="c1">// See if they have it</span>
</span><span class='line'>      <span class="k">return</span> <span class="nx">parent</span><span class="p">[</span><span class="nx">prop</span><span class="p">];</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>So now we support live lookups of parents, and, you know, some simplified genetics.</p>

<p>Isn&rsquo;t that just a simple, well-defined, example of how straightforward inheritance can be in
JavaScript?</p>

<h2>Conclusion</h2>

<p>Sometimes these analogies get pretty crazy in my head, and I start to think that maybe
instead of trying to apply known examples in the outside world in order to help people
understand, it&rsquo;s often better to just let someone know why they might wanna use
inheritance in their programs!</p>

<p>I personally find the best Prototypal Inheritance analogy to be:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">defaults</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">zero</span><span class="o">:</span> <span class="mi">0</span><span class="p">,</span>
</span><span class='line'>  <span class="nx">one</span><span class="o">:</span> <span class="mi">1</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">myOptions</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">defaults</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">yourOptions</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">defaults</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// When I want to change *just* my options</span>
</span><span class='line'><span class="nx">myOptions</span><span class="p">.</span><span class="nx">zero</span> <span class="o">=</span> <span class="mi">1000</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// When you wanna change yours</span>
</span><span class='line'><span class="nx">yourOptions</span><span class="p">.</span><span class="nx">one</span> <span class="o">=</span> <span class="mi">42</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// When we wanna change the **defaults** even after we&#39;ve got our options</span>
</span><span class='line'><span class="c1">// even **AFTER** we&#39;ve already created our instances</span>
</span><span class='line'><span class="nx">defaults</span><span class="p">.</span><span class="nx">two</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="nx">myOptions</span><span class="p">.</span><span class="nx">two</span><span class="p">;</span> <span class="c1">// 2</span>
</span><span class='line'><span class="nx">yourOptions</span><span class="p">.</span><span class="nx">two</span><span class="p">;</span> <span class="c1">// 2</span>
</span></code></pre></td></tr></table></div></figure>


<p>So stop making everything so confusing and go program cool stuff, and ignore
my old presentations when I used these analogies.</p>

<p>&lt;3z</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Deploying JavaScript Applications]]></title>
    <link href="https://alexsexton.com/blog/2013/03/deploying-javascript-applications"/>
    <updated>2013-03-26T03:25:00-05:00</updated>
    <id>https://alexsexton.com/blog/2013/03/deploying-javascript-apps-with-scout-files</id>
    <content type="html"><![CDATA[<p><strong>Preface:</strong> Nothing in this post is necessarily new, or even anything I thought of first (save for a name or two). However,
I&rsquo;m writing it because I&rsquo;d like to start building some consistency and naming conventions around a few of the techniques
that I am using (and are becoming more common), as well as document some processes that I find helpful.</p>

<p>Much of this comes from my experience deploying applications at Bazaarvoice as a large third party vendor, and should
probably be tailored to your specific environment. I&rsquo;m sure someone does the <em>opposite</em> of me in each step
of this with good results.</p>

<p>Also, I fully understand the irony of loading a few MBs of GIFs in a post largely about performance,
but I like them. Any specific tools I mention are because I&rsquo;m familiar with them, not necessarily because there
are no good alternatives. Feel free to comment on other good techniques and tools below. Facts appreciated.</p>

<h2>You</h2>

<p>You work on a large app. You might be a third party, or you might not be. You might be on a team, or you might not be.
You want maximum performance, with a high cache rate and extremely high availability.</p>

<h3>Dev with builds in mind</h3>

<p><img src="https://alexsexton.com/images/js_app_deploy/gruntbuild.gif" alt="/images/js_app_deploy/gruntbuild.gif" /></p>

<p>Locally, you might run a static server with some <a href="http://requirejs.org/">AMD modules</a>, or a <a href="http://incident57.com/codekit/">&ldquo;precompile server&rdquo;</a>
in front of some <a href="http://sass-lang.com/">sass</a> and <a href="http://coffeescript.org/">coffeescript</a>, or <a href="http://browserify.org/">browserify</a> with
<a href="http://wiki.commonjs.org/wiki/Modules/1.1">commonjs modules</a>. Whatever you&rsquo;re doing in development is your choice and not the topic du jour.</p>

<p>The hope is that you have a way of taking your dev environment files and wrapping them up into concisely built and minified JavaScript
and CSS files. Ideally this is an <a href="http://requirejs.org/docs/optimization.html#basics">easy step</a> for you, otherwise, you&rsquo;ll tend to skip it.
<em>Optimize for ease of mind here.</em> I tend to disagree with the sentiment that <em>&lsquo;script tags are enough.&rsquo;</em> Try to manage your dependencies
in a single place, and that place probably isn&rsquo;t in the order of your script tags in your HTML. Avoiding this step is easy until it isn&rsquo;t.</p>

<h3>Loading what you need is better than byte shaving</h3>

<p>One technique at the build-stage that is ideal for performance, is building minimal packages based on likely use. At page load, you&rsquo;ll want
to load, parse, and execute as little JavaScript as possible. Require.js allows you to &ldquo;exclude&rdquo; modules from your builds and
<a href="https://github.com/requirejs/example-multipage/blob/master/tools/build.js#L8-L45">create separate secondary modules</a>. Rather than shaving bytes
in your app files, you can avoid loading entire sections of code. Most sections of an app have predictable entry points that you can listen for
before injecting more functionality.</p>

<p>In our current app, only a fraction of the users click on the button that causes a specific flow to popup. Because of this we can
save ~20kb of code at page load time, and instead load it as a mouse gets close to the button, or after a few seconds of inactivity (to prime the cache).
This technique will go a much longer way than any of your normal byte saving tricks, but is not always the easiest and for that reason is often avoided.</p>

<p><img src="https://alexsexton.com/images/js_app_deploy/delaypackage.gif" alt="/images/js_app_deploy/delaypackage.gif" /></p>

<p>Check your network panel the next time you have Gmail open to see how
<a href="http://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-reducing.html">Google feels about this technique</a>. They take an extra
step and bring the code in as text, and don&rsquo;t bother parsing or executing it until they need to. This is good for low-powered/mobile devices.</p>

<p>In fact, some Googlers released a library, <a href="https://github.com/google/module-server">Module Server</a>, that allows you to do some of this dynamically.
It works with lots of module formats. And technically you could just use it to see how it decides to break up your files, and then switch
over to fully static files after you get that insight. They presented on it at JSConf.eu 2012:</p>

<div class="embed-video-container"><iframe src="https://www.youtube.com/embed/mGENRKrdoGY "></iframe></div>


<p>So instead of using a microjs cross-domain communication library that your coworker hacked together, just delay loading <a href="https://github.com/oyvindkinsey/easyXDM">EasyXDM</a>
until you need to do cross domain form POSTs.</p>

<h3>Don&rsquo;t penalize modern users</h3>

<p>I&rsquo;m all for progressive enhancement, and have to support IE6 in our primary application. However, it pains me when modern browser users have to pay
a performance price for the sins of others. It&rsquo;s a good idea to try to support some level of &ldquo;conditional builds&rdquo; or &ldquo;profile builds.&rdquo; In the
AMD world, you can use the <a href="http://requirejs.org/docs/optimization.html#hasjs">has.js integration</a>, or if you&rsquo;re feeling especially dirty, a build pragma.
However, third-parties have written some pretty nifty tools for doing this as a plugin.</p>

<p>One of the best tools for this that I&rsquo;ve seen is <a href="https://github.com/jensarps/AMD-feature">AMD-feature</a>. It allows you
to use a set of known supported features to load the best fitting build for the current user. This can be great on mobile. You can silently switch
out jQuery with Zepto (assuming you stick to the shared subset). You can add and remove polyfills for the correct users. If 20% of your JavaScript
is loading for %3 of your users, something is backwards.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">define</span><span class="p">({</span>
</span><span class='line'>    <span class="s1">&#39;dropdown&#39;</span><span class="o">:</span> <span class="p">[</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="nx">isAvailable</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>                <span class="c1">// test if we are on iOS</span>
</span><span class='line'>                <span class="k">return</span> <span class="nx">iOS</span> <span class="o">?</span> <span class="kc">true</span><span class="o">:</span> <span class="kc">false</span><span class="p">;</span>
</span><span class='line'>            <span class="p">},</span>
</span><span class='line'>
</span><span class='line'>            <span class="nx">implementation</span><span class="o">:</span> <span class="s1">&#39;src/dropdown-ios&#39;</span>
</span><span class='line'>        <span class="p">},</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="nx">isAvailable</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>                <span class="c1">// if we end up here, we&#39;re not on iOS,</span>
</span><span class='line'>                <span class="c1">// so we can just return true.</span>
</span><span class='line'>                <span class="k">return</span> <span class="kc">true</span><span class="p">;</span>
</span><span class='line'>            <span class="p">},</span>
</span><span class='line'>            <span class="c1">// Naturally this is simiplified and doesn&#39;t actually</span>
</span><span class='line'>            <span class="c1">// imply Android</span>
</span><span class='line'>            <span class="nx">implementation</span><span class="o">:</span> <span class="s1">&#39;src/dropdown-android&#39;</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">]</span>
</span><span class='line'><span class="p">});</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// In your code, you would load your feature like this:</span>
</span><span class='line'>
</span><span class='line'><span class="nx">define</span><span class="p">([</span><span class="s1">&#39;feature!dropdown&#39;</span><span class="p">],</span> <span class="kd">function</span><span class="p">(</span><span class="nx">dropdown</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// The variable &#39;dropdown&#39; now contains</span>
</span><span class='line'>    <span class="c1">// the right implementation - no matter</span>
</span><span class='line'>    <span class="c1">// what platform the code is executed on,</span>
</span><span class='line'>    <span class="c1">// and you can just do this:</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">myDropdown</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">dropdown</span><span class="p">();</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<h3>One less jpeg</h3>

<p>Lots of people like repeating this one. <del>I think <a href="http://paulirish.com/">Paul Irish</a> coined it</del> <a href="http://twitter.com/ajpiano">Adam J Sontag</a> naturally coined it, but the idea is if that if you loaded one less jpeg on your
site, you could fit in quite a bit of unshaved JavaScript in its place. Consider this the next time you are sacrificing readability or compatibility for file size.</p>

<p><img src="https://alexsexton.com/images/js_app_deploy/onelessjpg.gif" alt="/images/js_app_deploy/onelessjpg.gif" /></p>

<h2>Requests matter</h2>

<p>File size aside, the balance of a fast JS deployment lies somewhere between the number of requests, and the cachability of those requests.
It&rsquo;s often alright to sacrifice the cachability of a small script if you can inline it without causing an additional request. The exact balance
is not one that I could possibly nail down, but you can probably think of a file that is dynamic enough and small enough in your application
that might make sense to just print it inline in your page.</p>

<h3>Package all the pieces together</h3>

<h4>Fonts and Icons</h4>

<p>These days, these two are synonymous. I really like using fonts as icons and have done so with great success. We try to find appropriate unicode
characters to map to the icons, but it can sometimes be a stretch. Drew Wilson&rsquo;s <a href="http://pictos.cc/server/">Pictos Server</a> is an incredible way
to get going with this technique, though I might suggest buying a font pack in the end for maximum performance (so you can package it with your
application).</p>

<p><img src="https://alexsexton.com/images/js_app_deploy/pictos.png" alt="/images/js_app_deploy/pictos.png" /></p>

<p>First, we inline fonts as data URIs for supporting browsers. Then we fallback to referencing separate files (at the cost of a request), and then we fallback
to images (as separate requests). This means we end up with different builds of our CSS files. Each CSS build only includes one of the techniques,
so no one user is penalized by the way another browser might need fonts. The <a href="http://filamentgroup.com/">Filament Group</a> has a tool for this called
<a href="https://github.com/filamentgroup/grunticon">Grunticon</a>. I&rsquo;d highly recommend this technique. For every modern browser, you have a single
request for all styles and icons, with no additional weight from old IEs that don&rsquo;t support data-URIs.</p>

<h4>CSS Files</h4>

<p>It&rsquo;s typically the case that updates to JavaScript files necessitate changes to CSS as well. So these files usually have the same update times. For that
reason it&rsquo;s pretty safe to package them together.</p>

<p>So, as part of our build step, we first build our necessary CSS for our package into a file (for Bazaarvoice: styles are dependencies of templates,
which are dependencies of views, which are dependencies of the separate module packages we&rsquo;re loading, so this is an automatic step). Then we
read this file in, minify it, and inject it as a string in our main JavaScript file. Because we have control over when the templates are
rendered, we can just inject the CSS into a style tag before rendering the template. We have to render on the serverside occasionally, as well,
and in these cases I would recommend against this technique to avoid a flash of unstyled content.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">css</span>   <span class="o">=</span> <span class="s1">&#39;#generated{css:goes-here;}&#39;</span><span class="p">;</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">head</span>  <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">head</span> <span class="o">||</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementsByTagName</span><span class="p">(</span><span class="s1">&#39;head&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">],</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">style</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">createElement</span><span class="p">(</span><span class="s1">&#39;style&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">style</span><span class="p">.</span><span class="nx">type</span> <span class="o">=</span> <span class="s1">&#39;text/css&#39;</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="k">if</span> <span class="p">(</span><span class="nx">style</span><span class="p">.</span><span class="nx">styleSheet</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">style</span><span class="p">.</span><span class="nx">styleSheet</span><span class="p">.</span><span class="nx">cssText</span> <span class="o">=</span> <span class="nx">css</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">else</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">style</span><span class="p">.</span><span class="nx">appendChild</span><span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">createTextNode</span><span class="p">(</span><span class="nx">css</span><span class="p">));</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Only assume you have a &lt;head&gt; if you control</span>
</span><span class='line'><span class="c1">// the outer page.</span>
</span><span class='line'><span class="nx">head</span><span class="p">.</span><span class="nx">appendChild</span><span class="p">(</span><span class="nx">style</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Since we inline the fonts and icons into our CSS files, and then inline the CSS into our JS file (of which only 1 is injected on load), we end up with
a single packaged app that contains fonts, icons, styles, and application logic. The only other request will be necessary media and the data (we&rsquo;ll
get to those).</p>

<p>You may notice that we now have a couple of combinations of packages. <strong>Yep.</strong> If we have 3 ways to load fonts/icons multiplied by the number of
build profiles that we chose to create (mobile, oldIE, touch, etc), we can get 10-20 combinations fast. I consider this a really good thing. When you
generate them, have some consistent way of naming them, and we&rsquo;ll be able to choose our <em>exact</em> needed app for a user, rather than a lot of extra
weight for other users.</p>

<p>Quick Note: Old IEs can be fickle with inlining a lot of CSS. Just test your stuff and if it breaks, just fall back to link tag injection for oldIEs.</p>

<h2>The Scout File</h2>

<p>This post actually started out as a means to solidify this term. Turns out I am a bit more long-winded than I anticipated.</p>

<p>The <strong>Scout File</strong> or <strong>Scout Script</strong> is the portion of JavaScript that decides which package needs to be loaded. It kicks off
every process that can happen in parallel, has a low cache time, and is as small as possible.</p>

<p>It gets its name from being a small entity that looks out of the cache from time to time to warn everybody else that things have
changed. It&rsquo;s &lsquo;scouting&rsquo; for an app update and gathering data.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// Simplified example of a scout file</span>
</span><span class='line'><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// Feature test some stuff</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">features</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">svg</span><span class="o">:</span> <span class="nx">Modernizr</span><span class="p">.</span><span class="nx">svg</span><span class="p">,</span>
</span><span class='line'>    <span class="nx">touch</span><span class="o">:</span> <span class="nx">Modernizr</span><span class="p">.</span><span class="nx">touch</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// The async script injection fanfare</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">script</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">createElement</span><span class="p">(</span><span class="s1">&#39;script&#39;</span><span class="p">);</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">fScript</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementsByTagName</span><span class="p">(</span><span class="s1">&#39;script&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">baseUrl</span> <span class="o">=</span> <span class="s1">&#39;//cool-cdn.com/bucket/&#39;</span> <span class="o">+</span> <span class="nx">__BUILDNUM__</span> <span class="o">+</span> <span class="s1">&#39;/&#39;</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Build up a file url based on the features of this user</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">featureString</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">;</span>
</span><span class='line'>  <span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="k">in</span> <span class="nx">features</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="nx">features</span><span class="p">.</span><span class="nx">hasOwnProperty</span><span class="p">(</span><span class="nx">i</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="nx">features</span><span class="p">[</span><span class="nx">i</span><span class="p">])</span> <span class="p">{</span>
</span><span class='line'>      <span class="nx">featuresString</span> <span class="o">+=</span> <span class="s1">&#39;-&#39;</span> <span class="o">+</span> <span class="nx">i</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  <span class="kd">var</span> <span class="kr">package</span> <span class="o">=</span> <span class="s1">&#39;build&#39;</span> <span class="o">+</span> <span class="nx">featureString</span> <span class="o">+</span> <span class="s1">&#39;.js&#39;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Set the URL on the script</span>
</span><span class='line'>  <span class="nx">script</span><span class="p">.</span><span class="nx">src</span> <span class="o">=</span> <span class="nx">baseUrl</span> <span class="o">+</span> <span class="kr">package</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Inject the script</span>
</span><span class='line'>  <span class="nx">fScript</span><span class="p">.</span><span class="nx">parentNode</span><span class="p">.</span><span class="nx">insertBefore</span><span class="p">(</span><span class="nx">script</span><span class="p">,</span> <span class="nx">fScript</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Start loading the data that you know you can grab right away</span>
</span><span class='line'>  <span class="c1">// JSONP is small and easy to kick off for this.</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">dataScript</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">createElement</span><span class="p">(</span><span class="s1">&#39;script&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Create a JSONP Url based on some info we have.</span>
</span><span class='line'>  <span class="c1">// We&#39;ll assume localstorage for this example</span>
</span><span class='line'>  <span class="c1">// though a cookie or url param might be safer.</span>
</span><span class='line'>
</span><span class='line'>  <span class="nb">window</span><span class="p">.</span><span class="nx">appInitData</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">initialData</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// Get it to the core application when it eventually</span>
</span><span class='line'>    <span class="c1">// loads or if it&#39;s already there.</span>
</span><span class='line'>    <span class="c1">// A global is used here for ease of example</span>
</span><span class='line'>    <span class="nb">window</span><span class="p">.</span><span class="nx">comeGetMe</span> <span class="o">=</span> <span class="nx">initialData</span><span class="p">;</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// If we&#39;re on a static site, the url might tell us</span>
</span><span class='line'>  <span class="c1">// the data we need, and the user cookie might customize</span>
</span><span class='line'>  <span class="c1">// it. Simplified.</span>
</span><span class='line'>  <span class="nx">dataScript</span><span class="p">.</span><span class="nx">src</span> <span class="o">=</span> <span class="s1">&#39;//api.mysite.com&#39;</span> <span class="o">+</span>
</span><span class='line'>                   <span class="nb">document</span><span class="p">.</span><span class="nx">location</span><span class="p">.</span><span class="nx">pathname</span> <span class="o">+</span>
</span><span class='line'>                   <span class="s1">&#39;?userid=&#39;</span> <span class="o">+</span>
</span><span class='line'>                   <span class="nx">localStorage</span><span class="p">.</span><span class="nx">getItem</span><span class="p">(</span><span class="s1">&#39;userid&#39;</span><span class="p">)</span> <span class="o">+</span>
</span><span class='line'>                   <span class="s1">&#39;&amp;callback=appInitData;&#39;</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Inject it</span>
</span><span class='line'>  <span class="nx">fScript</span><span class="p">.</span><span class="nx">parentNode</span><span class="p">.</span><span class="nx">insertBefore</span><span class="p">(</span><span class="nx">dataScript</span><span class="p">,</span> <span class="nx">fScript</span><span class="p">);</span>
</span><span class='line'><span class="p">})();</span>
</span></code></pre></td></tr></table></div></figure>


<p>If you&rsquo;re a third party or have little control over the pages you&rsquo;re injected on, you&rsquo;ll probably use a file. Otherwise, the code
should be small enough and dynamic enough to warrant inlining on a page.</p>

<h3>Build apps into self-contained folders</h3>

<p>When you build your application, you end up with a set of static files in a folder. Take this folder of files and assign a build number to it.
Then upload this to a distributed content delivery network. <a href="http://aws.amazon.com/s3/">S3</a> with <a href="http://aws.amazon.com/cloudfront/">CloudFront</a>
on top of it is an easy choice. The <a href="https://github.com/pifantastic/grunt-s3">Grunt S3 Plugin</a> is a good way to do this with the Grunt toolchain.
Bazaarvoice has an Akamai contract, so we tend to use them, but the idea is that you are getting your built files onto servers that are geographically
close to your users. It&rsquo;s easy and cheap. Don&rsquo;t skimp! Latency is king.</p>

<p>Now that you have an app on a static CDN, make sure it gets served gzipped (where appropriate, grunt-s3 can help with this), and then set the cache
headers on your built files to <strong>forever</strong>. Any changes will get pushed as a different set of built files in a totally different folder, these
files should be guaranteed to never change. The only exception to this rule is the <strong>Scout File</strong>, which lives <em>outside</em> of the build folders in the root
directory.</p>

<p>The scout file for our third-party app is a very small JS file that contains a build number and a bit of JavaScript to determine the  build profile
that needs to be loaded. It also contains the minimum amount of code to determine the initial data that we&rsquo;re going to need for a page. It doesn&rsquo;t
have jQuery, or really any dependencies, it just does exactly what it needs to do. This file is cached for about 5 minutes (should be relatively short, but
close to the average session length).</p>

<h3>Parallelizing the initial data request</h3>

<p>Many people use each of their models to make separate requests for data once the app is loaded. Unfortunately, this is terrible for performance. Not only
are there multiple requests, but they can&rsquo;t be fired off until the BIG app files are loaded and executed. We want to parallelize the loading of our app
and our data. This is going to be tough for some folks, but it&rsquo;s a huuuge performance win.</p>

<p>We use node.js to run our models at build time. We feed in each of the &ldquo;page types&rdquo; that we know how to handle. For each of these page types, each model registers
its intent to load data, and we build up a hash of data that is needed for each page type and stick that into the scout file.</p>

<p>Then we had our API folk create a batch API so we can make multiple data requests at once. We use this hash of needed data for each page type (we have less than
10 page types, and you probably do too) in order to fire off a single request for the data that <strong>all</strong> the models will need, before they are loaded. Unfortunately
the way to do this changes drastically based on your framework, but it&rsquo;s worth your time!</p>

<h3>Statically generate your container pages and CDN them too</h3>

<p>If you aren&rsquo;t rendering templates on the server, then there&rsquo;s likely no reason you shouldn&rsquo;t be statically compiling all of your page shells at their
appropriate urls, and uploading them to a static CDN along with your scripts. This is a <em>huge</em> performance improvement.</p>

<p>Distributing the HTML to geographically close servers can have big wins towards getting to your actual content more quickly. In the case that you are uploading your static HTML
pages up to the static cdn along with your JS Application, your HTML files can become your Scout File. Put a small cache on each static HTML
page and inline the contents that you would have put in a scout file. This serves the same purpose as before, except we&rsquo;ve saved a request. The only thing
that isn&rsquo;t highly cached on a close-by server is the data, and we&rsquo;re already loading that in parallel with our app if we&rsquo;ve followed the previous instructions.</p>

<p>This means the main URL for your site is just a CNAME to a Cloudfront url. Doesn&rsquo;t that just <strong>sound</strong> nice? Talk about good uptime! Of course that
means the dynamic parts of your site would come from a subdomain like <code>api.mysite.com</code> or similar. The reduced latency of your initial HTML can be
a very nice win for performance since you&rsquo;ve inlined a scout file to immediately load the rest of the app in parallel.</p>

<p>The smart peeps at <a href="http://nodejitsu.com/">Nodejitsu</a> put out <a href="http://blacksmith.jit.su/">Blacksmith</a> to help with static site generation a while
back, but there are <a href="http://blog.bmannconsulting.com/node-static-site-generators/">plenty of options</a>. Many apps are single page apps with
only an <code>index.html</code> file anyways, so you can skip the static generation all together.</p>

<h3>All this together</h3>

<p>The goal in all of this is to:</p>

<ul>
<li>geographically cache <em>anything</em> that&rsquo;s static, not just images and jQuery.</li>
<li>cache your app until it changes, but not much longer.</li>
</ul>


<p>The folder structure I normally see is something like:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'><span class="c"># Simplified for Ease of Eyes</span>
</span><span class='line'>| S3-Bucket-1
</span><span class='line'>  |- app
</span><span class='line'>     |- b1234
</span><span class='line'>        |- build.js
</span><span class='line'>        |- build-svg.js
</span><span class='line'>        |- build-optional.css
</span><span class='line'>     |- b1235
</span><span class='line'>        |- build.js
</span><span class='line'>        |- build-svg.js
</span><span class='line'>        |- build-optional.css
</span><span class='line'>     |- b1236
</span><span class='line'>        |- build.js
</span><span class='line'>        |- build-svg.js
</span><span class='line'>        |- build-optional.css
</span><span class='line'>  |- index.html <span class="c"># or scout.js</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>index.html</code> file is the only thing that changes, everything else is just <em>added</em>. If we&rsquo;re a third party, it&rsquo;d be the <code>scout.js</code> file since we&rsquo;d be included in someone
else&rsquo;s markup. Everything else has a 30yr cache header. We can upload our build into a folder, verify it, and then switch the build number in the scout file.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// Simplification of the above process</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">build</span> <span class="o">=</span> <span class="s1">&#39;__BUILD__&#39;</span><span class="p">;</span> <span class="c1">// Replaced at build time</span>
</span><span class='line'><span class="nx">injectApp</span><span class="p">(</span><span class="s1">&#39;/app/&#39;</span> <span class="o">+</span> <span class="nx">build</span> <span class="o">+</span> <span class="s1">&#39;/build.js&#39;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Deploying a new version of the app becomes &ldquo;updating one variable.&rdquo; This means that every user on the site will have a fully updated app in the amount
of time you cached your scout file for. In our case it&rsquo;s 5 minutes. It&rsquo;s a pretty good trade off for us. We get lifetime caching for our big files and media,
but have a very quick turn around time for critical fixes and consistent roll-outs. It also means that if we ever need to roll back, it&rsquo;s a single variable
change to get people fully back on the old code. Clean up old builds as you feel is necessary.</p>

<h3>Other media requests</h3>

<p>Naturally, you&rsquo;ll have some logo images, or some promo images to load as part of the app. These should probably just be <a href="http://imageoptim.com/">imageOptim</a>&rsquo;d,
and sprited as best as possible. However, there is usually a second class of media on a site. Usually these are thumbnails and previews and avatars and such.
For these files, I&rsquo;d suggest using a mechanism to lazy load these media files. Make sure you&rsquo;re doing smart things with scroll event handlers (hint: throttling
the hell out of them), but you don&rsquo;t want to load 50 avatars if the user is 1000px away from that part of your app. Just be smart about this stuff. It&rsquo;s not
really my intent to cover this portion of app performance since it&rsquo;s not entirely related to deployment.</p>

<h2>Wrap Up</h2>

<p>There&rsquo;s nothing that surprising about these techniques. Everything that could possibly be statically generated is statically generated,
and thrown out on edge-cached servers. Every piece of functionality that isn&rsquo;t needed on page load, isn&rsquo;t loaded on page load. Everything that <em>is</em> needed
is loaded in parallel right away. Everything is cached forever, save for the scout file and the data request (you can save recent requests in local storage though!).</p>

<p>You aren&rsquo;t left with much else to optimize. You are always only loading and executing the minimum amount of JavaScript, and saving it for the maximum amount
of time. Naturally the more common tips of not going overboard with external libraries, and paying attention to render performance, and serving HTML with the
page response are all ways to change the performance (usually for the better), but this architecture fits well with many of today&rsquo;s more app-like deployments.</p>

<p>There&rsquo;s something really comforting about exposing a minimal dynamic API that needs to be fast and having everything else served out of memory from nearby
static servers. You should totally try it.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Introducing The Jed Toolkit]]></title>
    <link href="https://alexsexton.com/blog/2012/10/introducing-the-jed-toolkit/"/>
    <updated>2012-10-06T11:24:00-05:00</updated>
    <id>https://alexsexton.com/blog/2012/10/introducing-the-jed-toolkit</id>
    <content type="html"><![CDATA[<h2>The Jed Internationalization Toolkit</h2>

<p>The Jed Toolkit is a collection of interoperable tools to help facilitate
the full process of internationalizing applications in JavaScript.
These tools have a wide range of utility, from small modules to help
format messages, dates, and numbers to services that facilitate translation,
and code integration. The goal of the project is to bring the experience and
quality of internationalizing JavaScript applications up to par with the rest
of the current state of JavaScript tooling.</p>

<p>I&rsquo;m in the process of moving everything over, but you&rsquo;ll likely want to watch
this space: <a href="https://github.com/jedtoolkit">github.com/jedtoolkit</a> and <a href="http://jedtoolkit.org">jedtoolkit.org</a></p>

<h2>The Dojo Foundation and Future</h2>

<p>I&rsquo;m excited that The Jed Toolkit has been accepted into the Dojo Foundation so
its users can be sure that it will be a safe, unencumbered resource for them
into the future. I&rsquo;m extremely happy to be part of a family that includes
require.js, sizzle, and the dojo toolkit.</p>

<p>After being tasked with internationalizing a large application that I was building
I quickly realized that there was little available for JavaScript developers. I had
been using Gettext in a python application a few weeks prior, and decided it might be nice to
implement in JavaScript. So I did. I called it &ldquo;<a href="https://github.com/jedtoolkit/Jed">Jed</a>&rdquo; (soon to be gettext2.js) after
<a href="https://twitter.com/jedschmidt">Jed Schmidt</a>, everybody&rsquo;s favorite &ldquo;hobbyist&rdquo; JavaScripter / Japanese translator.</p>

<p>I was drawn to this problem because there were so few people considering its intricacies, but
I was shown by some very smart folks that there was a lot more to internationalization than
the little library I wrote. So I wrote another library, and ported a few others.</p>

<p>I was quite happy with how these were turning out. They weren&rsquo;t especially hard to create,
because most of them follow well-documented specifications. I really liked how ICU
MessageFormat made a lot of decisions based on how translators think, instead of how
programmers think. But naturally, they locked away that goodness behind a syntax/grammar
that no non-programmer should ever have to deal with. MessageFormat is great for translations
but not for translators. Not in the real world at least. That&rsquo;s when I realized that the problem was not (only) the tools for <em>writing</em>
international apps, but even deeper: in the tools and integration with translators.</p>

<h2>It&rsquo;s all about tools</h2>

<p>The translation space hasn&rsquo;t grown much since computers first existed.
We can barely encode files correctly in 2012. However, in other spaces, like content authoring,
we have a whole system of tools and integrations to map non-technical users&#8217; intent to structured
usable data for consumption. If your local tech writer wants to start a blog, they can! They
don&rsquo;t need to know how to set up a server or that HTML even exists.</p>

<p>The process of getting an app translated is cumbersome, and is a blocker to getting
good applications out there. FTP zips and crazy XML specs mixed with Word Documents rule
the landscape. There are no decent apis, or automatic integrations that anybody is using
at scale. I want to set out to change this.</p>

<p>Translators aren&rsquo;t all to blame. If you were a translator and got the message &ldquo;fair&rdquo;, would
you translate it as a carnival, or as &lsquo;just&rsquo;? We set our translators up for failure with
our context. We can do better. We can describe messages, and their variables. We can offer
examples and photos of the context. We can even translate the app in real time and they
can see their translation literally running in the place it will live.</p>

<p>The goal of the Jed I18n Toolkit is to help make the internationalization process much more
accurate and enjoyable for all parties. We should be able to write our messages directly in our templates
in whatever format we think is best. Our messages should be automatically culled, and deduped
and sent into a translation queue. The translator shouldn&rsquo;t be presented with anything other than
things that help them translate. The programmer&rsquo;s format should be irrelevant. Context is king, and
a bunch of crazy sprintf characters and html are just noise. When the translations are done, they should exist as
a service or api and be updated in real time. Gone should be the days of the 2 month translation code freeze.
You should be able to write a post commit hook that gets your translations through the system as fast
as you can find someone to translate them.</p>

<p>There&rsquo;s a lot to decide on how to bring all of these ideas into the project in a generic, but still
usable way, and it will take some time to get everything right. Right now I&rsquo;m starting by putting
in the few open source projects that are already out there as well as showing early beta work on some
of the integration tools. Please be patient with me and send me your suggestions and frustrations
so we can finally bring internationalization out of the dark ages.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Third Party JavaScript In The Third Person]]></title>
    <link href="https://alexsexton.com/blog/2012/08/third-party-javascript-in-the-third-person/"/>
    <updated>2012-08-08T21:35:00-05:00</updated>
    <id>https://alexsexton.com/blog/2012/08/third-party-javascript-in-the-third-person</id>
    <content type="html"><![CDATA[<p>At the end of last year I spoke at the awesome <a href="http://capitoljs.com/">CapitolJS</a> Conference in DC. I was encouraged to talk a little more broadly about third-party JavaScript development and its various quirks. When I got back home to <a href="http://austinjavascript.com/">AustinJS</a> we had some time for a short talk. Luckily, <a href="https://twitter.com/llbbl">Logan Lindquist</a> is usually there to film talks for <a href="http://www.austintechvideos.com/">Austin Tech Videos</a>. Long story short, my talk and slides are now available for <em>Third Party JavaScript in the Third Person</em>.</p>

<iframe width="560" height="315" src="https://www.youtube.com/embed/A-eu14Apb5o" frameborder="0" allowfullscreen></iframe>


<p>The slides are available (likely in webkit) at: <a href="https://alexsexton.com/talks/thirdparty">alexsexton.com/talks/thirdparty</a></p>

<p>I can&rsquo;t thank Logan enough for doing <a href="http://www.austintechvideos.com/">Austin Tech Videos</a>. It&rsquo;s a treasure trove of all kinds of talks from around town.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Third Party Front-end Performance]]></title>
    <link href="https://alexsexton.com/blog/2012/04/third-party-front-end-performance-part-1/"/>
    <updated>2012-04-11T14:36:00-05:00</updated>
    <id>https://alexsexton.com/blog/2012/04/third-party-front-end-performance-part-1</id>
    <content type="html"><![CDATA[<p>I work for a company called <a href="http://developer.bazaarvoice.com/">Bazaarvoice</a>. Our core products (Ratings and Reviews is our biggest) are all implemented as third party javascript applications. We are white-label, so you don&rsquo;t see a ton of our brand around, but we power the User Generated Content (UGC) behind Walmart, Samsung, Best Buy, Proctor &amp; Gamble, etc, etc. Needless to say, we have one of the highest volume third party applications on the internet. Fun stuff. There are other massively successful and smart companies doing similar things (take a look at Disqus or even peek into the Google or Facebook button code).</p>

<h2>Performance Matters</h2>

<p>Our core applications were built nearly 7 years ago, and gained features everyday over that period of time. As you can imagine, performance started to suffer. Since we&rsquo;re on the product page of major retailers, we knew that this wouldn&rsquo;t stand. I was tasked with re-thinking our solution with performance at the forefront of our architectural and deployment strategies. I attacked three different types of performance at varying levels of depth.</p>

<ul>
<li>Network</li>
<li>Injection/Rendering</li>
<li>Application</li>
</ul>


<p>Bazaarvoice has a developer blog that I sometimes write for, so I wrote an article on <a href="http://blog.developer.bazaarvoice.com/2012/04/11/third-party-front-end-performance-part-1/">Third Party Front-end Performance</a>. Normally I don&rsquo;t just link across, but I think this information is actually fairly applicable to a large chunk of developers. So check it out. Feel free to comment either place. Part 2 and 3 to come.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The UX of Language]]></title>
    <link href="https://alexsexton.com/blog/2012/03/the-ux-of-language/"/>
    <updated>2012-03-28T00:13:00-05:00</updated>
    <id>https://alexsexton.com/blog/2012/03/the-ux-of-language</id>
    <content type="html"><![CDATA[<p>I once read a tweet <del>that I haven&rsquo;t been able to attribute back to its original source</del> (<a href="http://paulirish.com/">Paul Irish</a> has sleuthed and found the original source to be a <a href="https://twitter.com/#!/thegdb/statuses/148293778019581952">Greg Brockman tweet</a>), but said something along the lines of</p>

<blockquote><p>Web programming is the science of coming up with increasingly complicated ways of concatenating strings.</p></blockquote>

<p>I think that there&rsquo;s a good reason for this.</p>

<p>As we turn to the next chapter of the web and start building more web <em>applications</em>, rather than just web <em>documents</em>, we begin to need to mix language with data. This presents an extremely difficult challenge if you only have to consider a single language. Often times we have to support many.</p>

<p>While the data density in language increases on our sites and apps, we must consider the user who has to read those sentences. The goal is to offer interesting data to the user without just generating a table and without sounding like Borat writes the copy. You can spend as much time as you&rsquo;d like on the interaction and visual design, but if your app doesn&rsquo;t have a good flow, you&rsquo;re leaving the most important cards on the table: <strong>the content</strong>.</p>

<h2>Let&rsquo;s Focus on English for a Second</h2>

<blockquote><p>Number of Results: 15</p>

<p>in Number of Categories: 3</p></blockquote>

<p>This is the type of language that we&rsquo;ve all come to expect out of the web. It gets the point across, but I&rsquo;d argue that it&rsquo;s not very personal or natural. That may not matter in this particular example, but consider building anything social. Identity is becoming a huge part of the next wave of apps. If you want to have any chance at personalization or identity, then the following isn&rsquo;t going to cut it:</p>

<blockquote><p>Alex added 5 friend(s) to their group on March 19, 2012</p></blockquote>

<p>This is in stark contrast to some of the more popular social networks.</p>

<p><img src="https://alexsexton.com/images/uxoflang/google-mf2.png" alt="/images/uxoflang/google-mf2.png" /></p>

<p>Not only does this correctly address the correct pluralization for &lsquo;people&rsquo;, it also takes into consideration the offset from the total count of the 3 people that are listed explicitly. This attention to detail doesn&rsquo;t stop at decent pluralization, but also gender.</p>

<p><img src="https://alexsexton.com/images/uxoflang/facebook-mf.png" alt="/images/uxoflang/facebook-mf.png" /></p>

<p><img src="https://alexsexton.com/images/uxoflang/facebook-mf2.png" alt="/images/uxoflang/facebook-mf2.png" /></p>

<p>Remember the old days when Facebook used to refer to <em>everyone</em> as a &lsquo;their&rsquo;? That was weird. Don&rsquo;t fall into that trap. When it comes to good user experience, you can&rsquo;t ignore the text. If you can go through your app and find any sentence that you&rsquo;d write differently if it wasn&rsquo;t generated by a computer, you are reducing the effectiveness of that text and degrading the overall experience.</p>

<h2>Iteration</h2>

<p>Assuming you&rsquo;re sold on the idea of a proper language treatment of your app, let&rsquo;s try to solve the problem using some of the examples we&rsquo;ve already seen.</p>

<blockquote><p>There are X result(s)</p></blockquote>

<p>In JavaScript, the naïve solution would be to do something like the following:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="k">if</span> <span class="p">(</span> <span class="nx">X</span> <span class="o">===</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">return</span> <span class="s2">&quot;There is one result&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">else</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">return</span> <span class="s2">&quot;There are &quot;</span> <span class="o">+</span> <span class="nx">X</span> <span class="o">+</span> <span class="s2">&quot; results&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This results in a proper english sentence in all cases. That&rsquo;s great, but let&rsquo;s get a touch more complex. <strong>Now we want to support another language.</strong> The pluralization rules for English are different than the rules for French. If we want to support French, our solution starts looking more like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="k">if</span> <span class="p">(</span> <span class="nx">lang</span> <span class="o">===</span> <span class="s2">&quot;en&quot;</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span> <span class="nx">X</span> <span class="o">===</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="s2">&quot;There is one result&quot;</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  <span class="k">else</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="s2">&quot;There are &quot;</span> <span class="o">+</span> <span class="nx">X</span> <span class="o">+</span> <span class="s2">&quot; results&quot;</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">else</span> <span class="k">if</span> <span class="p">(</span> <span class="nx">lang</span> <span class="o">===</span> <span class="s2">&quot;fr&quot;</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span> <span class="nx">X</span> <span class="o">&gt;</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="s2">&quot;Le, there are &quot;</span> <span class="o">+</span> <span class="nx">X</span> <span class="o">+</span> <span class="s2">&quot; results&quot;</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  <span class="k">else</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="s2">&quot;Le, there is &quot;</span> <span class="o">+</span> <span class="nx">X</span> <span class="o">+</span> <span class="s2">&quot; result&quot;</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This quickly becomes an unscalable solution. You might be thinking &ldquo;Well, Alex, I never plan on internationalizing my app, so the rest of this article doesn&rsquo;t apply to me.&rdquo; &ndash; I&rsquo;d encourage you to consider the original example as a more pleasant English-only sentence:</p>

<blockquote><p>There are 8 results in 2 categories.</p></blockquote>

<p>Even when ignoring locale, we still have some combinatoric debts to pay. Let&rsquo;s check out the code for handling this naïvely:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="k">if</span> <span class="p">(</span> <span class="nx">ResCount</span> <span class="o">!==</span> <span class="mi">1</span> <span class="o">&amp;&amp;</span> <span class="nx">CatCount</span> <span class="o">!==</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">return</span> <span class="s2">&quot;There are &quot;</span> <span class="o">+</span> <span class="nx">ResCount</span> <span class="o">+</span> <span class="s2">&quot; results in &quot;</span> <span class="o">+</span> <span class="nx">CatCount</span> <span class="o">+</span> <span class="s2">&quot; categories.&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">else</span> <span class="k">if</span> <span class="p">(</span> <span class="nx">ResCount</span> <span class="o">===</span> <span class="mi">1</span> <span class="o">&amp;&amp;</span> <span class="nx">CatCount</span> <span class="o">!==</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">return</span> <span class="s2">&quot;There is one result in &quot;</span> <span class="o">+</span> <span class="nx">CatCount</span> <span class="o">+</span> <span class="s2">&quot; categories.&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">else</span> <span class="k">if</span> <span class="p">(</span> <span class="nx">ResCount</span> <span class="o">!==</span> <span class="mi">1</span> <span class="o">&amp;&amp;</span> <span class="nx">CatCount</span> <span class="o">===</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">return</span> <span class="s2">&quot;There are &quot;</span> <span class="o">+</span> <span class="nx">ResCount</span> <span class="o">+</span> <span class="s2">&quot; results in one category.&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">else</span> <span class="k">if</span> <span class="p">(</span> <span class="nx">ResCount</span> <span class="o">===</span> <span class="mi">1</span> <span class="o">&amp;&amp;</span> <span class="nx">CatCount</span> <span class="o">===</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">return</span> <span class="s2">&quot;There is one result in one category.&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is pretty painstaking even without the chore of translating it into other languages. You cannot split up the halves of the sentences safely (especially if you want multiple languages), because the two halves may not match. You can imagine that when gender is added to this sentence, things explode even further.</p>

<blockquote><p>Alex searched for an image. He found 5 results in one category.</p></blockquote>

<p>Now we have to multiply that logic times the number of gender choices. Most specs have 3 gender choices: &ldquo;male&rdquo;, &ldquo;female&rdquo;, and &ldquo;other&rdquo;. &ldquo;Other&rdquo; specifically is treated &ldquo;as if you cannot determine the gender of someone who is far away from you.&rdquo; In the case of this simple sentence, we&rsquo;d need twelve copies of the sentence &ndash; one for each combination of gender and plural form of the nouns.</p>

<h2>Gettext (jed)</h2>

<p>I recently released a library, <a href="http://slexaxton.github.com/Jed/">Jed</a>, for using Gettext style messages in JavaScript. Gettext is a GNU spec that&rsquo;s been around for ages. I had been exposed to a little bit of Gettext from my python days, and considered it to be the most popular solution to many of these problems. The main feature of Gettext is that you can decouple the messages from the plural-forms of a given language.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">pluralForms</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="s2">&quot;en&quot;</span> <span class="o">:</span> <span class="kd">function</span> <span class="p">(</span> <span class="nx">x</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span> <span class="nx">x</span> <span class="o">===</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>    <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
</span><span class='line'>  <span class="p">},</span>
</span><span class='line'>  <span class="s2">&quot;fr&quot;</span> <span class="o">:</span> <span class="kd">function</span> <span class="p">(</span> <span class="nx">x</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span> <span class="nx">x</span> <span class="o">&gt;</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>We now get back an index of sorts. &ldquo;Gettext&rdquo; refers to the lookup/loading/encoding mechanism more than anything, but with these plural forms we could do a lookup for the correct string, stored as data.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">translations</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="s2">&quot;en&quot;</span> <span class="o">:</span> <span class="p">{</span>
</span><span class='line'>    <span class="s2">&quot;somekey&quot;</span> <span class="o">:</span> <span class="p">[</span> <span class="s2">&quot;There is one result.&quot;</span><span class="p">,</span> <span class="s2">&quot;There are %s results.&quot;</span> <span class="p">]</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  <span class="s2">&quot;fr&quot;</span> <span class="o">:</span> <span class="p">{</span>
</span><span class='line'>    <span class="s2">&quot;somekey&quot;</span> <span class="o">:</span> <span class="p">[</span> <span class="s2">&quot;Le, there is %s result.&quot;</span><span class="p">,</span> <span class="s2">&quot;Le, there are %s results.&quot;</span> <span class="p">]</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">lang</span> <span class="o">=</span> <span class="s2">&quot;en&quot;</span><span class="p">;</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">msg</span> <span class="o">=</span> <span class="nx">sprintf</span><span class="p">(</span> <span class="nx">translations</span><span class="p">[</span> <span class="nx">lang</span> <span class="p">][</span> <span class="s2">&quot;somekey&quot;</span> <span class="p">][</span> <span class="nx">pluralForms</span><span class="p">[</span> <span class="nx">lang</span> <span class="p">](</span> <span class="nx">X</span> <span class="p">)</span> <span class="p">],</span> <span class="nx">X</span> <span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this case we&rsquo;re using <code>sprintf</code> style replacement after we do the key lookup. That tends to be the most common way to do substitution with Gettext. Now we have a solution that relies on data instead of one-off code blocks for each message. Also, if your sprintf supports positional variables, you can now solve the problem that different languages order sentences differently than english does.</p>

<p>Soon after I released Jed it was shared on es-discuss. Immediately <a href="http://norbertlindenberg.com/">Norbert Lindenberg</a> stepped up to tell me that I was making a mistake by choosing Gettext. How right he was. The best example of my oversight is actually one that we&rsquo;ve already seen:</p>

<blockquote><p>There are 8 results in 2 categories</p></blockquote>

<p>How would we represent this in Gettext&rsquo;s PO format? The plural-form functions can only take a single number to decide the plural form. This sentence would need to be split up again, which won&rsquo;t work across languages and often won&rsquo;t work well even in English. Gender can be added in by utlizing Gettext&rsquo;s <em>context</em> feature, but it only goes one level deep. What if I needed an actual context AND a gender selection?</p>

<p>Norbert was kind enough to point me in the direction of the ICU MessageFormat spec. I could quickly see that some smart people had thought about this a lot longer than I had. Using Jed for Gettext can still be nice if you already have invested in using Gettext in other parts of your stack, but I&rsquo;d generally suggest against it in favor of MessageFormat.</p>

<h2>ICU MessageFormat</h2>

<p><code>MessageFormat</code> is actually just a few specs pasted together, but they look similar. They may seem vaguely familiar to those who have ever used Java&rsquo;s <code>ChoiceFormat</code> utility. They are different in a few ways, but the important part is that they more or less solve multiple plurals and gender specificity without as much of the combinatorics game.</p>

<p>The <code>MessageFormat</code> spec contains <code>PluralFormat</code> and <code>SelectFormat</code> in the most common cases. Using the syntax in <code>PluralFormat</code> we can address multiple plurals in the same sentence. All the pluralization data is standardized and pulled from <a href="http://cldr.unicode.org/">CLDR</a> and not needed as user input. There are <em>keywords</em> that come back as a result for any given input number: &ldquo;zero&rdquo;, &ldquo;one&rdquo;, &ldquo;two&rdquo;, &ldquo;few&rdquo;, &ldquo;many&rdquo;, &ldquo;other&rdquo;. All languages can be roughly mapped to these keywords, and it is the basis for some of the keywords in the message.</p>

<p>I won&rsquo;t go in to much detail about the syntax, as that&rsquo;s not the point of this post.</p>

<h3>PluralFormat</h3>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">There</span> <span class="p">{</span><span class="nx">ResCount</span><span class="p">,</span> <span class="nx">plural</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">one</span> <span class="p">{</span><span class="nx">is</span> <span class="nx">one</span> <span class="nx">result</span><span class="p">}</span>
</span><span class='line'>        <span class="nx">other</span> <span class="p">{</span><span class="nx">are</span> <span class="err">#</span> <span class="nx">results</span><span class="p">}</span>
</span><span class='line'>      <span class="p">}</span> <span class="k">in</span> <span class="p">{</span><span class="nx">CatCount</span><span class="p">,</span> <span class="nx">plural</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">one</span> <span class="p">{</span><span class="nx">one</span> <span class="nx">category</span><span class="p">}</span>
</span><span class='line'>        <span class="nx">other</span> <span class="p">{</span><span class="err">#</span> <span class="nx">categories</span><span class="p">}</span>
</span><span class='line'>      <span class="p">}.</span>
</span></code></pre></td></tr></table></div></figure>


<p>Using <code>PluralFormat</code> we were able to decouple the pluralization of each of the nouns.</p>

<h3>SelectFormat</h3>

<p>Gender is usually handled via <code>SelectFormat</code> which works much like a <code>switch</code> statement (except <code>default</code> becomes <code>other</code>).</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="p">{</span><span class="nx">GENDER</span><span class="p">,</span> <span class="nx">select</span><span class="p">,</span>
</span><span class='line'>  <span class="nx">male</span> <span class="p">{</span><span class="nx">He</span><span class="p">}</span>
</span><span class='line'>  <span class="nx">female</span> <span class="p">{</span><span class="nx">She</span><span class="p">}</span>
</span><span class='line'>  <span class="nx">other</span> <span class="p">{</span><span class="nx">They</span><span class="p">}</span>
</span><span class='line'><span class="p">}</span> <span class="nx">just</span> <span class="nx">found</span> <span class="p">{</span><span class="nx">ResCount</span><span class="p">,</span> <span class="nx">plural</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">one</span> <span class="p">{</span><span class="nx">one</span> <span class="nx">result</span><span class="p">}</span>
</span><span class='line'>        <span class="nx">other</span> <span class="p">{</span><span class="err">#</span> <span class="nx">results</span><span class="p">}</span>
</span><span class='line'>      <span class="p">}</span> <span class="k">in</span> <span class="p">{</span><span class="nx">CatCount</span><span class="p">,</span> <span class="nx">plural</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">one</span> <span class="p">{</span><span class="nx">one</span> <span class="nx">category</span><span class="p">}</span>
</span><span class='line'>        <span class="nx">other</span> <span class="p">{</span><span class="err">#</span> <span class="nx">categories</span><span class="p">}</span>
</span><span class='line'>      <span class="p">}.</span>
</span></code></pre></td></tr></table></div></figure>


<p>At the top we are able to determine the gender to use and then reuse most of our code from above to have a multiple plural and gender-specific sentence in as few characters as possible. Exceedingly complex sentences can often still require nesting and combinatorics, but for the majority of cases, you can avoid repeating any logic.</p>

<p>There are also complex &lsquo;plugins&rsquo; that can be used. The <code>offset</code> option will help you generate sentences like in the google plus example earlier.</p>

<h3>NumberFormat</h3>

<p>Technically, I don&rsquo;t think <code>NumberFormat</code> is part of <code>MessageFormat</code> &ndash; but it is usually necessary to pull in. <code>NumberFormat</code> allows you to internationalize things that we haven&rsquo;t even covered yet. Ever consider that other countries use <code>,</code> characters where the US uses <code>.</code> and visa versa? Number format is how you handle numbers, percentages, and currencies across languages.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="mf">1234.5</span>       <span class="c1">//Decimal number</span>
</span><span class='line'><span class="nx">$1234</span><span class="p">.</span><span class="mi">50</span>     <span class="c1">//U.S. currency</span>
</span><span class='line'><span class="mf">1.234</span><span class="p">,</span><span class="mi">57</span><span class="err">€</span>    <span class="c1">//German currency</span>
</span><span class='line'><span class="mi">123457</span><span class="o">%</span>      <span class="c1">//Percent</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Tools</h2>

<h3><a href="https://github.com/SlexAxton/messageformat.js">messageformat.js</a></h3>

<p>Shortly after releasing Jed, I released <a href="https://github.com/SlexAxton/messageformat.js">messageformat.js</a>. It&rsquo;s a much less sexy name, but perhaps I&rsquo;ll fix that soon. Google also has an implementation for people using the Google Closure library: <a href="http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/i18n/messageformat.js">http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/i18n/messageformat.js</a>.</p>

<p>While both are likely to be sufficiently fast, I did implement <code>messageformat.js</code> as a compile to JS language. This means that at build time, you can &lsquo;precompile&rsquo; your messages and ditch the majority of the library. This creates some great opportunities to be able to include <code>MessageFormat</code> style strings directly inside of your precompilable templates and have it all compile to a series of string concats. The readme on the project page should be quite helpful to learn the syntax as well as the integration and api.</p>

<h3><a href="https://github.com/owiber/numberformat.js">numberformat.js</a></h3>

<p>My co-worker <a href="https://twitter.com/#!/owiber">Oliver Wong</a> was able to do a quick port of the Google Closure <code>NumberFormat.js</code> to not need Google Closure (under Apache 2).</p>

<h3>EDIT: <a href="http://momentjs.com/">moment.js</a></h3>

<p>If anyone was wondering how I handle dates in my JS apps, I figured I&rsquo;d add it here. Moment.js, by <a href="https://github.com/timrwood">Tim Wood</a> is a library that I lean on a lot. There are plenty of additional internationalization libraries that I could start adding (for collation and rtl, etc), but for right now, the built in localization, and friendly <code>ago</code> syntax of moment.js make for a great user experience around dates.</p>

<h3>All Together Now</h3>

<p>I plan on updating Jed to actually contain this group of tools rather than the Gettext ones. I think these tools better suit the needs of modern applications. I will certainly keep the old Jed (Gettext) code around for those that require that format. It&rsquo;s not terribly difficult to integrate with these tools separately now, though.</p>

<h2>Conclusion</h2>

<p>Language is important. It can get complex. A lot of incredibly bright people have been looking into the constraints of same-language message generation, as well as multi-langual message generation (the spec writers, not necessarily the library creators). These tools and/or ideas should be the starting point of any application that desires to have a good UX.</p>

<p>It doesn&rsquo;t matter how many drop-shadows or rounded-corners you have, the user shouldn&rsquo;t have to decode your words. The words are often the most valuable experience.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[My Thoughts on AMD]]></title>
    <link href="https://alexsexton.com/blog/2012/03/my-thoughts-on-amd/"/>
    <updated>2012-03-22T23:08:00-05:00</updated>
    <id>https://alexsexton.com/blog/2012/03/my-thoughts-on-amd</id>
    <content type="html"><![CDATA[<p>So I know it was cool to write blog posts about AMD <a href="http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition">(A CommonJS JavaScript Module Specification)</a> like a month ago, but I&rsquo;ve recently had the desire to put my two cents into the discussion. I am likely not entirely objective &ndash; as I frequently use <a href="http://requirejs.org/">RequireJS</a> and have even committed <a href="https://github.com/jrburke/requirejs/commits/master?author=SlexAxton">tiny little parts</a> to the project that <a href="http://tagneto.blogspot.com/">James</a> likely had to rewrite. I would like to point out up front, though, that AMD <code>!==</code> RequireJS. RequireJS is an implementation of AMD plus a whole ecosystem of usefulness.</p>

<p>I recently had some in-depth discussions with <a href="http://twitter.com/tomdale">Tom Dale</a> who wrote a pretty popular article <a href="http://tomdale.net/2012/01/amd-is-not-the-answer/">against AMD</a>. Tom is a good friend and I respect all of his opinions. I wouldn&rsquo;t say that he&rsquo;s since &lsquo;come around&rsquo; on the AMD issue, though I may have worn his desire to fight against it. I&rsquo;ll take what I can get. His business partner and all-around web-tech badboy <a href="http://twitter.com/wycats">Yehuda Katz</a> remains less convinced and sent me a few questions that he wanted answered. I won&rsquo;t add them here verbatim, but I&rsquo;ll try and touch on a lot of that stuff as well. I think we more or less agree these days (but he by no means necessarily endorses what I&rsquo;m writing here). I&rsquo;ll explain.</p>

<p>I&rsquo;m going to opt to try and not rehash the great responses to Tom&rsquo;s concerns by <a href="http://tagneto.blogspot.com/2012/01/reply-to-tom-on-amd.html">James</a>, <a href="http://geddesign.com/post/15994566577/amd-is-the-answer">Dave</a>, and <a href="http://blog.millermedeiros.com/amd-is-better-for-the-web-than-commonjs-modules/">Miller</a>.</p>

<h2>AMD is not a script loader</h2>

<p>This misconception is likely propagated by the fact that RequireJS shows up on all of the script loader shootouts. I have written most of my thoughts on this already in my most popular (read: only) Quora answer: <a href="http://www.quora.com/What-are-the-use-cases-for-RequireJS-vs-Yepnope-vs-LABjs">What are the use cases for RequireJS vs Yepnope vs LABjs</a>. I&rsquo;ll mostly just leave it at this: <em>Script loading is a means in which AMD/RequireJS meets their requirements. It&rsquo;s neither a focus of the project or an integral part to using AMD in production</em>.</p>

<h2>AMD makes async loading possible, not required</h2>

<p>I often hear that people don&rsquo;t have an interest in asynchronous modules. This is perfectly fine. There are tons of integrated systems in full stack web frameworks that do a lot of great things for preprocessing that just don&rsquo;t require asynchronous script loading to be great.</p>

<p><strong>AMD is also so <em>other</em> people can include your module asynchronously.</strong></p>

<p>So if you have your app split up into modules via some preprocessor system, that&rsquo;s fine, but if you&rsquo;d like your code to be accessible to people who don&rsquo;t run the exact same stack as you: AMD works everywhere.</p>

<p>So write all your code how you like it, and right before you release it on github, consider adding this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nx">define</span> <span class="o">===</span> <span class="s1">&#39;function&#39;</span> <span class="o">&amp;&amp;</span> <span class="nx">define</span><span class="p">.</span><span class="nx">amd</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">define</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="nx">TheModule</span><span class="p">;</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="c1">// Feel free to also leak the global and/or test for a CJS enironment.</span>
</span></code></pre></td></tr></table></div></figure>


<p>And to take this a step further, I&rsquo;d encourage the preprocessing systems to just process <em>to</em> AMD.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// Node style modules</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;x&#39;</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">y</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;y&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">res</span> <span class="o">=</span> <span class="nx">doSomething</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">exports</span><span class="p">.</span><span class="nx">module</span> <span class="o">=</span> <span class="nx">res</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Instead of preprocessing this code to work on the web by just concatenating the globals in the correct order, why not just use AMD? It could easily be translated at preprocess time to:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">define</span><span class="p">([</span><span class="s1">&#39;x&#39;</span><span class="p">,</span><span class="s1">&#39;y&#39;</span><span class="p">],</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span><span class="nx">y</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">res</span> <span class="o">=</span> <span class="nx">doSomething</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">);</span>
</span><span class='line'>  <span class="k">return</span> <span class="nx">res</span><span class="p">;</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now you have a module that anyone can pick up (and translate it into their own module format if they&rsquo;d like).</p>

<p>The problem with using anyone else&rsquo;s format is that AMD is the only format that is suited well for asynchronous loading. This is not important to one group of people, but it is important to a different group of people, and is a valid concern in web development. In this case, AMD is the inclusive module format.</p>

<p>As for &lsquo;synchronous&rsquo; module loading with AMD, the api must use the asynchronous pattern, but if a module is already registered, the result is atomic. Not to mention that it&rsquo;s perfectly valid to use the <code>require('x');</code> syntax when you can be sure a module already exists. The syntax <em>allows</em> for asynchronous loading, but it doesn&rsquo;t require you to load things that way.</p>

<p>If you don&rsquo;t like parts about AMD, and prefer to preprocess, that&rsquo;s fine. I would encourage you to process to AMD though. Much like JavaScript is a common compilation target, I&rsquo;d like to see AMD become that as well, for modules. It won&rsquo;t help when in 5 years every project handles modules with their own preprocessor format.</p>

<h2>AMD requires preprocessing anyways, right?</h2>

<p>Yep, but not until build time. Any sane user of RequireJS uses the amazing <a href="https://github.com/jrburke/r.js/">r.js</a> build tool before pushing to production. So why not just preprocess on request and output &ldquo;modules&rdquo; in the correct order and wrap them in a big IIFE?</p>

<p>It would likely work, but in my opinion there is value in being able to develop directly out of a folder, with only static resources. It&rsquo;s the reason that so many new developers are using LESS.js &ndash; just load the file and go. It doesn&rsquo;t require you to install a watcher, or set up rails, or even learn how to install an additional whole programming language to your highly varied OS landscape. AMD works without all the stuff. It is a developer experience with immediate gratification.</p>

<p>Many people disagree with the sentiment that our tools should all be able to run on the client side in order to facilitate the idea that our web pages can run out of static directories. I definitely agree that there are tons of uses for preprocessors that run outside of the browser, but I don&rsquo;t fundamentally agree that modules are part of the &lsquo;just nice to have if you can figure out the watchers&rsquo; group of tools. <em>Real</em> modules are going into browsers soon, and I think they should be part of the first class citizen group of tools that we run in our browsers. Not to mention, if you do opt-in to using a pre-processor and you want someone else&rsquo;s preprocessor to be able to understand your modules, you&rsquo;ll have to agree on a standard compilation target anyways. What better than AMD?</p>

<p>Much of what James writes about in his posts are about how there are a few &lsquo;meh&rsquo; things about AMD, but that it meets nearly every requirement of a module system better than any alternative. He doesn&rsquo;t often mention AMD as a compilation target, but I think it solves everyone&rsquo;s problems.</p>

<h2>It&rsquo;s not nearly as &lsquo;complex&rsquo; as you think it is.</h2>

<p>AMD is implemented by attaching a scriptloader to an object. Load something, store it in the object, if someone else asks for it, pull it back out. Much of the size in RequireJS is for other amazing features and developer tooling. You can switch out RequireJS in production with <a href="https://github.com/jrburke/almond">Almond</a> &ndash; it is 857 bytes.</p>

<p>The other notion is that it&rsquo;s a chore to write. If we ignore the fact that most modern code editors could easily store the boilerplate for you, I would argue that it&rsquo;s actually less characters than <em>not</em> doing it. Also, (nearly) everyone who says this also complains that it forces them to nest their code an extra level, and then they turn around and immediately wrap all of their code in an IIFE.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// An IIFE for leakage. One level of nesting.</span>
</span><span class='line'><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="c1">// require statement per dependency</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;path/x&#39;</span><span class="p">),</span>
</span><span class='line'>        <span class="nx">y</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;path/y&#39;</span><span class="p">),</span>
</span><span class='line'>        <span class="nx">z</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;path/z&#39;</span><span class="p">),</span>
</span><span class='line'>        <span class="nx">a</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;path/a&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">doStuff</span><span class="p">();</span>
</span><span class='line'>  <span class="nx">exports</span><span class="p">.</span><span class="nx">module</span> <span class="o">=</span> <span class="p">{</span> <span class="p">...</span> <span class="p">};</span> <span class="c1">// if you&#39;re doing more commonjs type stuff, not always</span>
</span><span class='line'><span class="p">})(</span><span class="k">this</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here&rsquo;s the same AMD module:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">require</span><span class="p">([</span>
</span><span class='line'>    <span class="s1">&#39;path/x&#39;</span><span class="p">,</span>
</span><span class='line'>    <span class="s1">&#39;path/y&#39;</span><span class="p">,</span>
</span><span class='line'>    <span class="s1">&#39;path/z&#39;</span><span class="p">,</span>
</span><span class='line'>    <span class="s1">&#39;path/a&#39;</span>
</span><span class='line'><span class="p">],</span> <span class="kd">function</span> <span class="p">(</span> <span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">,</span> <span class="nx">z</span><span class="p">,</span> <span class="nx">a</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">doStuff</span><span class="p">();</span>
</span><span class='line'>  <span class="k">return</span> <span class="p">{</span> <span class="p">...</span> <span class="p">};</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>~36% less to type, by my quick and dirty measure (stripping whitespace and counting chars). It can be even less if you don&rsquo;t have any dependencies and just include a define at the end of your file like we did in a previous example.</p>

<p>Sure there&rsquo;s a level of nesting, but it&rsquo;s one that you&rsquo;ll need to put there regardless of whether you&rsquo;re using AMD or not. Sure that can be generated at request time, but so can the AMD callback function boilerplate.</p>

<h2>Why not just polyfill ES6 Modules?</h2>

<p>Well, first off, they&rsquo;re not entirely baked. David Herman &ndash; the author of the original Module proposal &ndash; just posted a pretty delicious update for some ideas for a <a href="https://mail.mozilla.org/pipermail/es-discuss/2012-March/021543.html">simpler and sweeter module syntax</a>.</p>

<p>Secondly, I think it&rsquo;s a great idea. As soon as the syntax settles back down I think we could all consider setting up preprocessors to allow for the syntax in the browser. This would require a request-time preprocessor because of the invalid nature of the syntax. So if you were able to run a preprocessor, then I think you should use the ES Harmony Module syntax. I think it should then compile to AMD, obviously, but you shouldn&rsquo;t ever have to worry about it.</p>

<h2>Quick RequireJS plug</h2>

<p>I obviously like AMD a decent amount, but I also think RequireJS is a fantastic tool in my stack. The &lsquo;plugin&rsquo; architecture is not incredibly well-documented, but it essentially acts as module middleware. My favorite application of this feature involves templates.</p>

<p>I use the pattern in my <a href="https://github.com/SlexAxton/require-handlebars-plugin">require-handlebars-plugin</a> to great effect. Rather than require a precompiled template during dev mode, I simply prefix my module name, and the template compilation occurs before the callback is invoked.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// In a no template middleware world</span>
</span><span class='line'><span class="nx">require</span><span class="p">([</span><span class="s1">&#39;handlebars&#39;</span><span class="p">,</span> <span class="s1">&#39;text!someTemplate.hbs&#39;</span><span class="p">],</span> <span class="kd">function</span> <span class="p">(</span> <span class="nx">Handlebars</span><span class="p">,</span> <span class="nx">strTemplate</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">fnTemplate</span> <span class="o">=</span> <span class="nx">Handlebars</span><span class="p">.</span><span class="nx">compile</span><span class="p">(</span> <span class="nx">strTemplate</span> <span class="p">);</span>
</span><span class='line'>  <span class="nx">fnTemplate</span><span class="p">({</span><span class="s2">&quot;some&quot;</span><span class="o">:</span> <span class="nx">data</span><span class="p">});</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is also similar to the technique where templates are stored in <code>type="script/tmpl"</code> script tags and pulled in by their id. This means that if you want to compile your templates at build time, you need to fundamentally alter every location that retrieves a template.</p>

<p>With the hbs template plugin, this is handled for you.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// With require-handlebars-plugin</span>
</span><span class='line'><span class="nx">require</span><span class="p">([</span><span class="s1">&#39;hbs!someTemplate&#39;</span><span class="p">],</span> <span class="kd">function</span> <span class="p">(</span> <span class="nx">fnTemplate</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">fnTemplate</span><span class="p">({</span><span class="s2">&quot;some&quot;</span><span class="o">:</span><span class="nx">data</span><span class="p">});</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>During development, this loads the template in as text and precompiles it for you. At build time it automatically outputs a precompiled module that is concatenated into the build. This ability alone is like magic to me and I just wanted to tell everyone how much I like it.</p>

<h2>Conclusion</h2>

<p>You don&rsquo;t have to like AMD more than whatever you use. It would be nice if we had a standard, compatible web module syntax though. I think AMD is the best-suited candidate for that role, and that the preprocessors should use AMD as a compilation target, rather than a direct competitor. Obviously it&rsquo;s still cool if you just use it straight up, but that doesn&rsquo;t need to happen for it to succeed.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Uselessware :: A Brief History (JSConf 2011 Talk)]]></title>
    <link href="https://alexsexton.com/blog/2012/03/uselessware-a-brief-history-jsconf-2011-talk/"/>
    <updated>2012-03-20T01:15:00-05:00</updated>
    <id>https://alexsexton.com/blog/2012/03/uselessware-a-brief-history-jsconf-2011-talk</id>
    <content type="html"><![CDATA[<p>I felt like linking up this talk that I gave on Track B of JSConf in Portland this past year. I feel passionately about the value of writing code that serves no useful purpose other than to bring joy and skills to its implementors and users.</p>

<p>The talk is pretty short :D</p>

<iframe width="560" height="315" src="https://www.youtube.com/embed/JiXTVRXP_z0" frameborder="0" allowfullscreen></iframe>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A New Blogging Engine]]></title>
    <link href="https://alexsexton.com/blog/2012/03/new-blogging-engine/"/>
    <updated>2012-03-19T00:21:00-05:00</updated>
    <id>https://alexsexton.com/blog/2012/03/new-blogging-engine</id>
    <content type="html"><![CDATA[<p>All the cool kids are staticly generating these days. I&rsquo;m in.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Breaking The Cross Domain Barrier (Screencast)]]></title>
    <link href="https://alexsexton.com/blog/2011/06/breaking-the-cross-domain-barrier-screencast/"/>
    <updated>2011-06-06T00:00:00-05:00</updated>
    <id>https://alexsexton.com/blog/2011/06/breaking-the-cross-domain-barrier-screencast</id>
    <content type="html"><![CDATA[<p>I decided to try my hand at doing a screencast. I have been told my old cross-domain talk slides have always needed a little more context, so I did that. Hopefully I&#8217;ll get in the habit of doing these, they&#8217;re not so difficult. Enjoy!</p>




<iframe src="https://player.vimeo.com/video/24705559?title=0&amp;byline=0&amp;portrait=0" width="400" height="300" frameborder="0"></iframe>


<p><a href="https://vimeo.com/24705559">Breaking The Cross Domain Barrier</a> from <a href="https://vimeo.com/slexaxton">SlexAxton</a> on <a href="https://vimeo.com">Vimeo</a>.</p>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Breaking The Cross Domain Barrier (or half of it anyways)]]></title>
    <link href="https://alexsexton.com/blog/2010/11/breaking-the-cross-domain-barrier-or-half-of-it-anyways/"/>
    <updated>2010-11-30T00:00:00-06:00</updated>
    <id>https://alexsexton.com/blog/2010/11/breaking-the-cross-domain-barrier-or-half-of-it-anyways</id>
    <content type="html"><![CDATA[<p>I gave a talk at TXJS and AustinJS about cross domain communication in JavaScript. Here is a video that stopped halfway through that talk.</p>

<iframe src="https://player.vimeo.com/video/17342024?title=0&amp;byline=0&amp;portrait=0&amp;color=0" width="599" height="329" frameborder="0"></iframe>


<p><a href="https://vimeo.com/17342024">Breaking The Cross Domain Barrier</a> from <a href="https://vimeo.com/yayquery">yayQuery</a> on <a href="https://vimeo.com">Vimeo</a>.</p>


<p>The slides are available here: <a href="http://www.slideshare.net/SlexAxton/breaking-the-cross-domain-barrier">Breaking The Cross Domain Barrier</a></p>

<p>Sorry for the half-vid, and low quality, but I figured it was worth putting out there, as I&rsquo;ve had a few requests for it and I&rsquo;m running out of hard drive space. Perhaps with any pressure, I&rsquo;d do a screencast.</p>

<p>Also, this was the day that I took two green nyquil pills thinking that GREEN meant DAY (for dayquill). So I may be a little more relaxed than normal. I&rsquo;m sure the beer didn&rsquo;t help either. I rather liked it, if I recall.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[An Accessible Way To Stop Your Content From Flashing (FOUC)]]></title>
    <link href="https://alexsexton.com/blog/2010/09/an-accessible-way-to-stop-your-content-from-flashing-fouc/"/>
    <updated>2010-09-28T00:00:00-05:00</updated>
    <id>https://alexsexton.com/blog/2010/09/an-accessible-way-to-stop-your-content-from-flashing-fouc</id>
    <content type="html"><![CDATA[<p>There are a lot of different reasons why you might see content flash on your page before it&#8217;s done loading. The flash that I&#8217;m talking about usually happens when you are trying to build a JavaScript widget that gracefully degrades when JavaScript is off. You probably feel pretty cool about yourself for writing your JS in an accessible way, but you are sad that it hurts the user experience.</p>




<p>One of the most common examples of this situation happens with tabbed interfaces, and more specifically the jQuery UI Tab widget. You give it your group of divs and links to turn them into the tabs, but that code doesn&#8217;t run until domready. Before the dom is ready, you&#8217;re original content all shows on the page, then when the tab code runs, it gets hidden.</p>




<p>Please don&#8217;t set them to hidden in your CSS in order to stop this from happening. This hurts accessibility, SEO, and the laws of white-hat web development, because without JavaScrpt, this content can never be seen. Instead, try this little trick:</p>




<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;style </span><span class="na">type=</span><span class="s">&quot;text/css&quot;</span><span class="nt">&gt;</span>
</span><span class='line'><span class="c">/*</span>
</span><span class='line'><span class="c">Obviously this is not a real class name, but here you would just</span>
</span><span class='line'><span class="c">set all the elements you want to hide as display:none.</span>
</span><span class='line'><span class="c">You should probably make this style whatever the JavaScript ends</span>
</span><span class='line'><span class="c">up setting them to. That way you don&#39;t accidentally add weird styles.</span>
</span><span class='line'><span class="c">*/</span>
</span><span class='line'><span class="nc">.stuffIDontWantToFlash</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">display</span><span class="o">:</span><span class="k">none</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="nt">&lt;/style&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;noscript&gt;</span>
</span><span class='line'><span class="nt">&lt;style </span><span class="na">type=</span><span class="s">&quot;text/css&quot;</span><span class="nt">&gt;</span>
</span><span class='line'><span class="c">/*</span>
</span><span class='line'><span class="c">Inside of this noscript block, show the elements, this should behow</span>
</span><span class='line'><span class="c">you want it to look for people without JS - it could even be styled</span>
</span><span class='line'><span class="c">totally different for them if you&#39;d like to lay it out differently without</span>
</span><span class='line'><span class="c">tabs...</span>
</span><span class='line'><span class="c">*/</span>
</span><span class='line'><span class="nc">.stuffIDontWantToFlash</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">display</span><span class="o">:</span><span class="k">block</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="nt">&lt;/style&gt;</span>
</span><span class='line'><span class="nt">&lt;/noscript&gt;</span>
</span></code></pre></td></tr></table></div></figure>




<p>So there. Now we&#8217;re using the noscript tag to conditionally override our CSS hiding of the elements. You can technically do this with link tags as well, but since you need to put the noscript version in a separate place than the original style (which can be anywhere), it&#8217;s probably not worth the extra http request. Just make sure the noscript override version runs after the initial setting. Cascading at it&#8217;s finest.</p>




<p>I know what 2 of you are thinking: &#8220;OMG Gross. This does not validate, because a style tag can&#8217;t be anywhere except in the head element&#8221; - well, you could put it in the head element, but that could be weird. In other words, I don&#8217;t really care. It works everywhere.</p>




<p>
&lt;3z
</p>




<p>
Alex
</p>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[What I Learned about the Google Chrome Store]]></title>
    <link href="https://alexsexton.com/blog/2010/09/what-i-learned-about-the-google-chrome-store/"/>
    <updated>2010-09-18T00:00:00-05:00</updated>
    <id>https://alexsexton.com/blog/2010/09/what-i-learned-about-the-google-chrome-store</id>
    <content type="html"><![CDATA[<p>While traveling in Europe this week, I had the pleasure of going to a Google Chrome developer event put on by Mike Mahemoff (The Moff™) and Paul Kinlan (whom Paul Irish says is a genius, so that&rsquo;s a good start). I took some notes during the meeting. I didn&rsquo;t know tooo much about the chrome app store, so I figured I&rsquo;d post what I learned in a very digestible manner for anyone who&rsquo;s googling for the right keywords next week.</p>

<p>A bulleted list of things I learned at the meetup (other than how strong The Moff™ is in real life):</p>

<ul>
<li><p>Here were some slides for the night: <a href="http://3.ly/y2dd"><a href="http://3.ly/y2dd">http://3.ly/y2dd</a></a></p></li>
<li><p>No date on the official release of the store but apparently &ldquo;Coming soon&rdquo;</p></li>
<li><p>There will be a free and a pay model, but the pay model is only launching in the US (then other markets to follow)</p></li>
<li><p>There will be a way to do billing monthly/yearly/onetime (paypal (&ldquo;harder&rdquo;, not sure of the specifics)/googlecheckout)</p></li>
<li><p>There will be an API to see if the user really bought something</p></li>
<li><p>5% of your revenue is theirs, rest is yours (yay) (way better than 30% &ndash; wowy)</p></li>
<li><p>Apps aren&rsquo;t chrome specific. They say they&rsquo;d love to make stuff work cross browser, but they are going a little bit different direction from W3C widget spec&hellip;</p></li>
<li><p>Pay to install</p></li>
<li><p>You install apps directly into the browser</p></li>
<li><p>There will be a user-permission popup for (location, notifications, storage, etc)</p></li>
<li><p>Open now&hellip; I guess this means you can build stuff that works as a chrome app already (but there&rsquo;s no store)</p></li>
</ul>


<p>&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;-Second Half&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&ndash;</p>

<ul>
<li><p>Apps different than websites (even though theyre both web)</p></li>
<li><p>You CAN use flash/silverlight/java if you want, but they don&rsquo;t auto install, so if the user doesn&rsquo;t have them, you&rsquo;re SOL</p></li>
<li><p>Google hosted (if you want)</p></li>
<li><p>If you go Google hosted, they are packaged (let&rsquo;s get a spec for this going!), if not, just a URL and a manifest</p></li>
</ul>


<p>I stopped taking notes at this point to actually build a chrome app. It was insanely easy, so I&rsquo;m happy about that. Yay chrome apps. I&rsquo;d love to see how these pan out. I don&rsquo;t think it can work until they are cross-browser, etc, but half the fun of them is that if it&rsquo;s a chrome app, it doesn&rsquo;t have to work in FF, so you can use specific APIs&hellip; so it&rsquo;s a tradeoff.</p>

<p>Aiight. Tried to keep that as informal as possible. Hope someone wanted this info!</p>

<p>Alex</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[On "Rolling Your Own" Large jQuery Apps]]></title>
    <link href="https://alexsexton.com/blog/2010/08/on-rolling-your-own-large-jquery-apps/"/>
    <updated>2010-08-16T00:00:00-05:00</updated>
    <id>https://alexsexton.com/blog/2010/08/on-rolling-your-own-large-jquery-apps</id>
    <content type="html"><![CDATA[<p>As a preface, make sure you&rsquo;ve read my super-smart and talented yayQuery co-host Rebecca Murphey&rsquo;s blog post on this topic</p>

<p>here: <a href="http://blog.rebeccamurphey.com/on-jquery-large-applications">On jQuery Large Applications</a> and here: <a href="http://blog.rebeccamurphey.com/on-rolling-your-own">On Rolling Your Own</a>.</p>

<p>Rebecca points out some huge holes in the jQuery-verse when it comes to large-application development, and gives her opinion on why she doesn&rsquo;t think jQuery is ever a good fit for a large application. I disagree, and she&rsquo;s successfully convinced me to write a post on why I think what I do, so here we are.</p>

<p>Also, please, no one point out that I prefer Django over Pylons, which is essentially the same argument :D . The difference, though, is that I think Pylons is awesome, and that people should totally be using it for large applications on the backend, as long as they prefer it!</p>

<p>First, I will start by mentioning that I have written several large applications using jQuery, and that I think that from a &lsquo;framework&rsquo; perspective, something like Dojo (which Rebecca supports) or YUI3 serves as a much better core to a large application than jQuery. However, arguing that &lsquo;you shouldn&rsquo;t use jQuery in your large application&rsquo; is an entirely different topic. jQuery does not describe or prevent any framework of application development, so you are free to choose your own to suit your needs. I do not advocate the incorrect use of jQuery as the core of your application. I do advocate JavaScript at the core of your application, though.</p>

<p><strong>jQuery is a tool </strong>(lolz)</p>

<p>I build large applications that <em>use </em>jQuery. I don&rsquo;t build large applications <em>on top</em> of jQuery. This incredibly important distinction hasn&rsquo;t been very well clarified thus far in the conversation. I think it&rsquo;s a fair ambiguity, however, because while it&rsquo;s possible to use jQuery in well-structured ways, it&rsquo;s certainly the road less travelled. The &lsquo;common jquery user&rsquo; tends to throw everything onto the jQuery namespace, and pull in everything as plugins, and generally very tightly couple their applications to jQuery. I think the distinction is still important for the argument, because it doesn&rsquo;t rule out the fact that you can write some really nice applications using jQuery.</p>

<p><strong>It&rsquo;s not jQuery, it&rsquo;s you.</strong></p>

<p>I think the thought that people are incapable of using jQuery in this manner stems from quite a few bad consulting experiences with companies using jQuery for no reason other than the fact that it&rsquo;s <code>the cool thing to do,</code> but using it entirely in an entirely backwards manner. This is also not a good way of making library decisions (at least in the long term). It doesn&rsquo;t reflect poorly on the code in jQuery so much as it reflects poorly on either the messaging from the jQuery team, or just the general population&rsquo;s inability to write good code and tendency to do what&rsquo;s popular. However, if Dojo were the hip-cool-designer library, they would suffer from <em>the exact same problem</em>.</p>

<p>Any library, in the hands of people who don&rsquo;t know what they&rsquo;re doing (even FuseJS), will not serve the needs of the application. This is a reality for anything that becomes popular. It&rsquo;s easy to like Dojo for the quality of code that comes out of it, but that&rsquo;s because the significantly less amount of people who use it are <strong>really good JavaScript Developers</strong>. That&rsquo;s important.</p>

<p>Being a good JavaScript developer before you start writing your application is the key to building good large applications. <em>It&rsquo;s not what library you use. </em>This is why I write about inheritance in JavaScript for the majority of my large jQuery apps articles. It&rsquo;s the JS people need to learn. In fact, I&rsquo;d imagine there&rsquo;d be some insanely backwards code from people using Dojo who didn&rsquo;t know what they were doing. You have to remain level-headed, though, and try to evaluate the tools without bringing in your past experiences with other developers. You can certainly choose Dojo to get away from jQuery noobs, but recommending Dojo to jQuery noobs is just bringing your problem along with you.</p>

<p><strong>Roll it.</strong></p>

<p>Aiight, with all that out of the way (yikes), let me give my most objective reasoning possible for why I think it&rsquo;s ok to use jQuery in a large app. Please keep in mind that I&rsquo;m not advocating against Dojo or YUI3, I&rsquo;m advocating against the absolute notion that &lsquo;jQuery should never be used for large applications.&rsquo; Use what you prefer, of course.</p>

<p>Rebecca&rsquo;s core argument against rolling your own jQuery large app is that 1) no one else knows your code-base, so supporting is harder, and 2) the solutions in a library like Dojo are built to work together by smart people who have thought long and hard about the problems, and rolling your own are more fragile and can cause issues with upgrade paths and compatibility, etc. These are valid points, but I think they are painted with a narrow frame of reference for the type of app structure you might use in a large jQuery app.</p>

<p>It&rsquo;s common knowledge that a separation of concerns is key to any large application. Loose-coupling is something that I&rsquo;ve blogged extensively about in the past. If you have a problem updating a portion of your application, it&rsquo;s because you wrote it too coupled. This is not unique to jQuery. Dojo&rsquo;s API stays about as backwards-compatible as they come (seriously), but that doesn&rsquo;t mean your old code will just work. In fact one of the few experiences I&rsquo;ve had with DojoX code is that some of the less popular DojoX modules often need changes to return the correct values, or not throw errors. The core of the library, has been significantly more impressive in regards to this, but we&rsquo;re talking about code that <em>you </em>write, not the library core.  I am a fan of Dojo&rsquo;s backwards compatibility efforts over jQuery&rsquo;s. Changing an API in a point release isn&rsquo;t always the most friendly change for devs.</p>

<p>Her list of requirements for a large app is well considered. It is a comprehensive list of things that often come in handy when building a large application. All of these things have been answered by smart people, in the JavaScript community. Much like her example with templating, you can decide which pieces to use (except, directly, not with library specific code&hellip;). Instead of overriding Dojo.templated you just change out the contents of your template rendering function with the new one. If you correctly loosely-coupled your application, then &lsquo;yay&rsquo;, you switched out a part of your app in less lines of code!</p>

<p>Here&rsquo;s the list of things that she&rsquo;d expect from a framework, along with the appropriate solutions I&rsquo;d consider:</p>

<ul>
    <li><strong>DOM manipulation tools</strong> - jQuery core</li>
    <li><strong>Ajax tools</strong> - jQuery core</li>
    <li><strong>A dependency management and build system</strong> - RequireJS</li>
    <li><strong>Clear patterns for code organization, such as namespaced modules</strong> - The module pattern and a few object literals</li>
    <li><strong>An inheritance system, preferably one that offers multiple inheritance, for sharing code across modules and staying DRY</strong> - modules +$.extend</li>
    <li><strong>A non-DOM-centric, loosely coupled API for communication between modules</strong> - pub/sub || custom events</li>
    <li><strong>A widget system that makes use of the inheritance system, with lifecycle management (setup/teardown) and templating</strong> - $.fn + mustache/microtemplates</li>
    <li><strong>A system for maintaining templates separate from JavaScript while interning them into the build to eliminate HTTP requests</strong> - &lt;script &#8220;text/html&#8221;&gt; + text!requirejsdependency</li>
    <li><strong>A system for abstracting RESTful server communication</strong> - assumes you <em>want</em> REST - but $.ajax usually works anyways&#8230;</li>
    <li><strong>For a UI-intensive project, a rich widget system pluggable to arbitrary data sources and designed with an easily-extended API</strong> - jQuery UI or ExtJS on jQuery</li>
    <li><strong>For an enterprise project, a11y and i18n provisions, as well as clear patterns for file organization </strong>- jQuery UI has many of these, you can also build them in. Require dictates some directory structure.</li>
</ul>


<p>These requests are pretty obviously skewed to someone who likes working in Dojo. They are all pretty awesome ways to do things, but to say that you needed the module pattern is to entirely overlook other very valid ways of structuring complex code. Of course Dojo offers ways to do things like event-oriented programming over object-oriented. The point here is that, if Dojo has answered every question, and jQuery and friends has also answered every question (perhaps not in the same place), it&rsquo;s going to be <em>just as hard</em> to pick up the code base and figure out what&rsquo;s going on. I could structure my Dojo app in a way that Rebecca doesn&rsquo;t like, and use template overrides for template-languages that she despises, and I could tightly couple my dom elements and their attributes to my data, and it&rsquo;d all be in beautiful Dojo. That Dojo has answered all the questions does not facilitate that you understood those answers or that you agree with them.</p>

<p><strong>The positives</strong></p>

<p>I somewhat reject the notion that using jQuery, Underscore, Require, Mustache, and the module pattern (as facilitated by Require) is &ldquo;rolling your own.&rdquo; Sure you piece them together, by choosing how you use them, but you do the exact same thing when you choose how you use the various parts of Dojo. I think that all of these tools are as strong as the Dojo alternatives. You can argue that you could use any of these tools with Dojo because it&rsquo;s so flexible that you can put anything in, but then you can&rsquo;t argue that &lsquo;rolling your own&rsquo; is bad, because that&rsquo;s what you just did. Either use Dojo, or agree that sometimes, it&rsquo;s not that bad to pull in a different way of thinking, you can&rsquo;t have it both ways.</p>

<p>jQuery normalizes things across browsers when you need it to, and serves as a mostly-fantastic way of doing dom-manip and ajax. If you use it according to it&rsquo;s strengths, you still can choose some really strong software alongside it that was specifically designed to be awesome at what it does.</p>

<p>Underscore gives you a very solid utility library, much like you&rsquo;d find in Dojo, and it&rsquo;s extensible to boot. You can use it in two of the major paradigms natively, and it falls back to native implementations when it can. It&rsquo;s hardly fragile, and it&rsquo;s insanely easy to integrate into your project. It&rsquo;s no worse or better than Dojo&rsquo;s offering.</p>

<p>RequireJS is likely going to be <em>used </em>in Dojo 2.0 and James Burke, who wrote Require, also wrote most of the Dojo dependency management system. Require incorporates all the sweet stuff from Dojo, plus some really awesome future stuff coming from the CommonJS peeps. Some apps, though, don&rsquo;t require a ton of dependency management. Single page apps are likely not going to be terribly dependency heavy, and if you want&hellip; you can leave out the dependency management system all-together, and still use your modules, just like you always wanted. You can switch it out for LabJS if you want speed too.</p>

<p>Templating was the example that Rebecca used to show that she could roll her own templating style in Dojo. She used mustache instead of the default Dojo offering. I can&rsquo;t argue against that. I&rsquo;m in favor of pulling together the correct tools for the job.</p>

<p>A lot of what is nice about Dojo, is it&rsquo;s prescribed format for creating modules. There&rsquo;s quite a bit of flexibility, but anyone who could understand the way that Dojo does this could easily understand some of the basic underlying patterns that it&rsquo;s enhancing. I can use object.create and the module pattern to my hearts content to structure my app, and that&rsquo;s not some &lsquo;wild tangent&rsquo; that no one will ever be able to unravel. It&rsquo;s a simple, and common pattern that you&rsquo;d be required to understand to use the Dojo method. Sure there&rsquo;s no prescribed way to exactly structure this, but that&rsquo;s the case with the &lsquo;extremely flexible&rsquo; Dojo offering as well.</p>

<p>I&rsquo;m not advocating creating super complex alternatives to Dojo&rsquo;s module structure. I think JavaScript offers a simple and flexible interface to creating and manipulating objects. I can choose which ever way I&rsquo;d like. The module pattern is 2 pages of of text and code examples in The Good Parts. Just go read that.</p>

<p><strong>TL;DR</strong></p>

<p>Dojo is a fantastic library that I would encourage you to pick up and add to your skillset. jQuery can be a fantastic tool to use as well. &ldquo;Rolling Your Own&rdquo; application with good tools alongside jQuery is no harder to understand than a Dojo app, nor is it harder to support, and it&rsquo;s likely more specific to your needs. The fragile part of your code isn&rsquo;t in the tools you use, it&rsquo;s in the code that you write around them.</p>

<p>I wish we&rsquo;d focus less on whether jQuery or LibX was a good or bad choice for large applications, and focus on the fact that people who don&rsquo;t know <strong>JavaScript</strong> are never going to write well-structured apps. Anyone who does understand the fundamental concepts behind JavaScript would be able to do it well with or without Dojo. Your language should provide your structure, and your toolkits should dictate your tools on top of that structure.</p>

<p>Learn JavaScript first. Then care about large apps. Then make a smart decision, according to your preferences, on which, if any, library you want to use.</p>

<p>-Slex</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[TXJS and ScriptJunkie]]></title>
    <link href="https://alexsexton.com/blog/2010/06/txjs-and-scriptjunkie/"/>
    <updated>2010-06-10T00:00:00-05:00</updated>
    <id>https://alexsexton.com/blog/2010/06/txjs-and-scriptjunkie</id>
    <content type="html"><![CDATA[<p>I have been pretty neglectful of my blog since I started at Bazaarvoice, but I think I&rsquo;m going to try to pick up a little bit. That being said, here&rsquo;s a short update.</p>

<p>I am now a featured author on <a href="http://msdn.microsoft.com/en-us/scriptjunkie">ScriptJunkie</a> &ndash; a new website from Microsoft about front end development. Check out my post <a href="http://msdn.microsoft.com/en-us/scriptjunkie/ff728622.aspx">&ldquo;Building and Maintaining Large JavaScript Applications&rdquo;</a></p>

<p>I&rsquo;ll likely cover a few more topics concerning large application structure in the future, both on my blog and on yayQuery and ScriptJunkie.</p>

<p>Also, TXJS happened. I&rsquo;d suggest going to the <a href="http://texasjavascript.com/">totally awesome webpage</a> and catching the slides and the speakerrate pages for all the talks to get caught up on how much awesomeness happened. Also, my fridge is still full of left over beer, so if you&rsquo;re in town&hellip; beer.js at my place.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Superclassy Inheritance with JavaScript Video]]></title>
    <link href="https://alexsexton.com/blog/2010/03/superclassy-inheritance-with-javascript-video/"/>
    <updated>2010-03-10T00:00:00-06:00</updated>
    <id>https://alexsexton.com/blog/2010/03/superclassy-inheritance-with-javascript-video</id>
    <content type="html"><![CDATA[<p>Here is the uncut director&rsquo;s edition of my talk given on February 20th, 2010 concerning Inheritance patterns in Javascript. Please forgive the rambling, and the bit of extra footage on either end of the talk.</p>

<object width="400" height="225"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="https://vimeo.com/moogaloop.swf?clip_id=9998565&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1" /><embed src="https://vimeo.com/moogaloop.swf?clip_id=9998565&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="225"></embed></object>


<p><a href="https://vimeo.com/9998565">Superclassy Inheritance with Javascript - Alex Sexton - NCJS 02/20/10</a> from <a href="https://vimeo.com/yayquery">yayQuery</a> on <a href="https://vimeo.com">Vimeo</a>.</p>


<p>&lt;3z</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using Inheritance Patterns to Organize Large jQuery Applications]]></title>
    <link href="https://alexsexton.com/blog/2010/02/using-inheritance-patterns-to-organize-large-jquery-applications/"/>
    <updated>2010-02-25T01:27:00-06:00</updated>
    <id>https://alexsexton.com/blog/2010/02/using-inheritance-patterns-to-organize-large-jquery-applications</id>
    <content type="html"><![CDATA[<p><img style="float: left; margin: 0 10px 10px 0;width:200px;height:150px;" src="https://alexsexton.com/wp-content/uploads/will.jpg" alt="Last will and testament - lolz" />
I want to introduce/reinforce a pattern for developing large applications with jQuery. I did not invent any of this, but I find that the resources that describe this technique are few and far-between.&ndash; so I&rsquo;m taking a shot at it.</p>

<p>By and large, when using jQuery, developers seem to forget the paradigms they learned for well structured code in other languages. This is likely due to the fact that jQuery is effectively neutral when it comes to your structural methodology or inheritance patterns, and therefore doesn&rsquo;t push someone in any one direction. Many times in other libraries (See Dojo Declare/Provide/Require, or MooTools Class, etc.), a paradigm is used and exclusively offered, and then code generally ends up more uniform than the oh-so-common-massive-jquery-indented-chains that I&rsquo;m sure you&rsquo;ve seen .</p>

<p>I&rsquo;m not going to necessarily suggest that you use any single inheritance pattern, as there are many options, and each makes sense for different people and different situations. I do however suggest that you know your options. There are a few good reads on the topic of Inheritance in javascript, and I would strongly suggest people read at least a bit of the following:</p>

<ul>
<li><a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742">Javascript: The Good Parts (Chapter 5)</a> -Douglas Crockford</li>
<li><a href="Javascript:%20The%20Good%20Parts%20(Chapter%205">Prototypal Inheritance in Javascript</a>) -Douglas Crockford</li>
<li><a href="http://www.amazon.com/Object-Oriented-JavaScript-high-quality-applications-libraries/dp/1847194141">Object-Oriented Javascript</a> -Stoyan Stefanov</li>
<li><a href="http://webreflection.blogspot.com/2010/02/javascript-override-patterns.html">Javascript Override Patterns</a> -Andrea Giammarchi</li>
<li><a href="http://ejohn.org/blog/simple-javascript-inheritance/">Simple JavaScript Inheritance</a> -John Resig</li>
</ul>


<p>Choosing your form of modularity is an important step. If you come from a background of highly-classical inheritance (I learned Java in school, so&hellip;I know that world) then perhaps starting with a classical implementation is going to be your best choice. If you are trying to stay slim and do the things a little more in the &ldquo;JavaScript way&rdquo; (a term that means essentially nothing), then you might try to use prototypal inheritance. For my examples, any form of inheritance will at least work on most accounts.</p>

<p>I&rsquo;ll jump straight to a code example of this technique in use, and then describe it&rsquo;s setup and structure:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="c">&lt;!-- Just an empty div to begin with --&gt;</span>
</span><span class='line'><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;mySpeaker&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then we&rsquo;ll run our javascript:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">$</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="c1">// Call a custom plugin for your object on a dom element</span>
</span><span class='line'>  <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#mySpeaker&#39;</span><span class="p">).</span><span class="nx">speaker</span><span class="p">({</span><span class="s1">&#39;name&#39;</span><span class="o">:</span> <span class="s1">&#39;Alex&#39;</span><span class="p">});</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Have quick access to the actual speaker object</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">mySpeaker</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#mySpeaker&#39;</span><span class="p">).</span><span class="nx">data</span><span class="p">(</span><span class="s1">&#39;speaker&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// The interface of the object that you build can</span>
</span><span class='line'>  <span class="c1">// wrap more complex dom manipulations that are</span>
</span><span class='line'>  <span class="c1">// separated from actual program logic.</span>
</span><span class='line'>  <span class="nx">mySpeaker</span><span class="p">.</span><span class="nx">speak</span><span class="p">(</span><span class="s1">&#39;I am a speaker.&#39;</span><span class="p">);</span> <span class="c1">// Results in a dom update</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// This shows automatic access to correct element in the dom</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>And the html now looks more like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;mySpeaker&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;h1&gt;</span>Alex<span class="nt">&lt;/h1&gt;</span>
</span><span class='line'>  <span class="nt">&lt;p&gt;</span>I am a speaker.<span class="nt">&lt;/p&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The key here is that we didn&rsquo;t have to call something like <strong>$elem.append(&lsquo;Alex&rsquo;)</strong> nor did we even have to consider what would happen when a <strong>speaker</strong> object was called with the <strong>speak()</strong> function. I consider this to be the key to modular development. This level of abstraction helps keep the <strong>how</strong> and the <strong>what</strong> separated (or &ldquo;loosely coupled&rdquo; &ndash; if you like buzzwords). The other thing that was important to note is that after we instantiate the plugin, we have a clear two-way path between our Object and our Dom Element &ndash; both have an easy way to immediately access the other. This is important, because we often have different points of entry to jump-start a routine, so being able to access the part that you need quickly and easily is important.</p>

<p>Implementing this technique is pretty simple, and should actually take less brain power to set up than traversing through the dom in your head to figure out a crazy chain.</p>

<p>Let&rsquo;s start with the <strong>Speaker</strong> object.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="cm">/**</span>
</span><span class='line'><span class="cm"> * Object Speaker</span>
</span><span class='line'><span class="cm"> * An object representing a person who speaks.</span>
</span><span class='line'><span class="cm"> */</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">Speaker</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">init</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">elem</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// Mix in the passed in options with the default options</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">options</span> <span class="o">=</span> <span class="nx">$</span><span class="p">.</span><span class="nx">extend</span><span class="p">({},</span><span class="k">this</span><span class="p">.</span><span class="nx">options</span><span class="p">,</span><span class="nx">options</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// Save the element reference, both as a jQuery</span>
</span><span class='line'>    <span class="c1">// reference and a normal reference</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">elem</span>  <span class="o">=</span> <span class="nx">elem</span><span class="p">;</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">$elem</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="nx">elem</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// Build the dom initial structure</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">_build</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// return this so we can chain/use the bridge with less code.</span>
</span><span class='line'>    <span class="k">return</span> <span class="k">this</span><span class="p">;</span>
</span><span class='line'>  <span class="p">},</span>
</span><span class='line'>  <span class="nx">options</span><span class="o">:</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">name</span><span class="o">:</span> <span class="s2">&quot;No name&quot;</span>
</span><span class='line'>  <span class="p">},</span>
</span><span class='line'>  <span class="nx">_build</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">$elem</span><span class="p">.</span><span class="nx">html</span><span class="p">(</span><span class="s1">&#39;&lt;h1&gt;&#39;</span><span class="o">+</span><span class="k">this</span><span class="p">.</span><span class="nx">options</span><span class="p">.</span><span class="nx">name</span><span class="o">+</span><span class="s1">&#39;&lt;/h1&gt;&#39;</span><span class="p">);</span>
</span><span class='line'>  <span class="p">},</span>
</span><span class='line'>  <span class="nx">speak</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">msg</span><span class="p">){</span>
</span><span class='line'>    <span class="c1">// You have direct access to the associated and cached jQuery element</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">$elem</span><span class="p">.</span><span class="nx">append</span><span class="p">(</span><span class="s1">&#39;&lt;p&gt;&#39;</span><span class="o">+</span><span class="nx">msg</span><span class="o">+</span><span class="s1">&#39;&lt;/p&gt;&#39;</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>I use an object literal here which puts me in the Prototypal Inheritance camp, I believe, but this is just an easily digestible pattern.</p>

<p>As you can see, there are easy-to-read, small functions, that have a clear purpose. In our use of this pattern, we call api type methods like <strong>speak()</strong> but not necessarily an internal method (like <strong>_build</strong>). You can hide your internal functions either by naming convention (not really hiding them), or by using something like the module pattern. In our simple example, I have just added an underscore to the beginning of the function to indicate that it&rsquo;s private.</p>

<p>Code that is organized like this is much easier to test and to change/read. This also allows you to change the way things function without changing the way that the Object api is used. For instance, we could change the <strong>speak</strong> method to alert the string instead of append it to the related element. We would have to change the internals of the <strong>speak</strong> function, but we could keep our call to it the same.</p>

<p>The bridge that we build is probably the most interesting part of this pattern. It&rsquo;s a different approach than many of the popular plugins take (slightly different than jquery ui), but it has a few really great benefits.</p>

<p>The most simple way to do this is by hand:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="c1">// Make sure Object.create is available in the browser (for our prototypal inheritance)</span>
</span><span class='line'><span class="c1">// Courtesy of Papa Crockford</span>
</span><span class='line'><span class="c1">// Note this is not entirely equal to native Object.create, but compatible with our use-case</span>
</span><span class='line'><span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span> <span class="o">!==</span> <span class="s1">&#39;function&#39;</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">o</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">function</span> <span class="nx">F</span><span class="p">()</span> <span class="p">{}</span> <span class="c1">// optionally move this outside the declaration and into a closure if you need more speed.</span>
</span><span class='line'>        <span class="nx">F</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="nx">o</span><span class="p">;</span>
</span><span class='line'>        <span class="k">return</span> <span class="k">new</span> <span class="nx">F</span><span class="p">();</span>
</span><span class='line'>    <span class="p">};</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">$</span><span class="p">){</span>
</span><span class='line'>  <span class="c1">// Start a plugin</span>
</span><span class='line'>  <span class="nx">$</span><span class="p">.</span><span class="nx">fn</span><span class="p">.</span><span class="nx">speaker</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// Don&#39;t act on absent elements -via Paul Irish&#39;s advice</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span> <span class="k">this</span><span class="p">.</span><span class="nx">length</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">each</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>        <span class="c1">// Create a new speaker object via the Prototypal Object.create</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">mySpeaker</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">Speaker</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">// Run the initialization function of the speaker</span>
</span><span class='line'>        <span class="nx">mySpeaker</span><span class="p">.</span><span class="nx">init</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="k">this</span><span class="p">);</span> <span class="c1">// `this` refers to the element</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">// Save the instance of the speaker object in the element&#39;s data store</span>
</span><span class='line'>        <span class="nx">$</span><span class="p">.</span><span class="nx">data</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="s1">&#39;speaker&#39;</span><span class="p">,</span> <span class="nx">mySpeaker</span><span class="p">);</span>
</span><span class='line'>      <span class="p">};</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'><span class="p">})(</span><span class="nx">jQuery</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>And that&rsquo;s it!</p>

<p>Now you have separated the creation of the plugin from the actual code itself. You are using the plugin to attach objects (with any inheritance patten) to dom elements and visa versa, but the plugin itself is just the connection and initialization code. This means that we could generalize this process further. I first saw this from Scott Gonzalez (of the jQuery UI team) and his code later became the &lsquo;widget factory&rsquo; in jQuery UI. I prefer to not pass strings into my plugins in order to call functions, but it&rsquo;s a valid approach as some people would take issue with having to pull out the object each time they started with a dom element.</p>

<p>Here is some code that might get you started writing/using a &lsquo;bridge&rsquo; function (bridge is what&rsquo;s found now in jQuery UI 1.8) that can help you attach your general code with a given plugin (since writing that same initialization plugin code multiple times would get old and defeat the whole DRY principle that our inheritance model has hopefully provided). This code is mostly courtesy of Scott Gonzalez because I couldn&rsquo;t think of a more stripped down elegant approach to this. I changed it to accept Objects instead of Constructor Functions because that works a little better with my example (prototypal inheritance). I also force it to call my <strong>init</strong> function in order to save myself an extra call. (<a href="http://pastie.org/517177">This example</a> shows Scott&rsquo;s use of this method along with John Resig&rsquo;s Simple-Inheritance implementation &ndash; also very cool.)</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">$</span><span class="p">.</span><span class="nx">plugin</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="nx">object</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">$</span><span class="p">.</span><span class="nx">fn</span><span class="p">[</span><span class="nx">name</span><span class="p">]</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                <span class="c1">// optionally, you could test if options was a string</span>
</span><span class='line'>                <span class="c1">// and use it to call a method name on the plugin instance.</span>
</span><span class='line'>      <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">each</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>          <span class="k">if</span> <span class="p">(</span> <span class="o">!</span> <span class="nx">$</span><span class="p">.</span><span class="nx">data</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">name</span><span class="p">)</span> <span class="p">)</span> <span class="p">{</span>
</span><span class='line'>              <span class="nx">$</span><span class="p">.</span><span class="nx">data</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">name</span><span class="p">,</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">object</span><span class="p">).</span><span class="nx">init</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="k">this</span><span class="p">));</span>
</span><span class='line'>          <span class="p">}</span>
</span><span class='line'>      <span class="p">});</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// With the Speaker object, we could essentially do this:</span>
</span><span class='line'><span class="nx">$</span><span class="p">.</span><span class="nx">plugin</span><span class="p">(</span><span class="s1">&#39;speaker&#39;</span><span class="p">,</span> <span class="nx">Speaker</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// At this point we could do the following</span>
</span><span class='line'><span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#myDiv&#39;</span><span class="p">).</span><span class="nx">speaker</span><span class="p">({</span><span class="nx">name</span><span class="o">:</span> <span class="s2">&quot;Alex&quot;</span><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>That&rsquo;s about all there is to it. I&rsquo;d encourage you to pick some pattern for your development that isn&rsquo;t just inline chaining of jQuery function calls. This way of breaking up and organizing functionality in your code serves as a quick and easy jumping-off point for testing and modularity. It&rsquo;s much easier to test the individual functions of a modular object than it is to write tests for a single-line chain of jQuery calls.</p>

<p>Also, I do get some feedback along the lines of &ldquo;well, my code is not a plugin&rdquo; &ndash; &ldquo;this isn&rsquo;t applicable to my code&rdquo; &ndash; but I usually tend to disagree. The stigma that a jQuery plugin has to be for general consumption is flawed. I encourage you to use the plugin architecture if you are creating functionality based on a dom element selection. For instance, if you are adding an error notification system, it would be very easy to create a notification object that attaches to a div and has the methods required for notification directly attached to it, rather than having a function that merely hides and shows random dom elements.</p>

<p>I am doing a round up of performance on a lot of this inheritance usage and I should get to writing another entry on that soon, but from my early tests, using reasonable inheritance is generally <strong>not that expensive</strong>. If you are pushing the limits of CPUs and browser rendering, you might have to make some sacrifices, but for the general case, the instantiation hit of inherited objects is probably well worth your while.</p>

<p>I&rsquo;d love to hear about the way you approach this problem.</p>
]]></content>
  </entry>
  
</feed>
