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

<channel>
	<title>etrium (Dan&#039;s stuff)</title>
	<atom:link href="http://www.etrium.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.etrium.co.uk</link>
	<description>Nerdtastic</description>
	<lastBuildDate>Sun, 22 May 2011 11:16:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>The right way to add AJAX support to your site</title>
		<link>http://www.etrium.co.uk/2011/05/22/the-right-way-to-add-ajax-support-to-your-site/</link>
		<comments>http://www.etrium.co.uk/2011/05/22/the-right-way-to-add-ajax-support-to-your-site/#comments</comments>
		<pubDate>Sun, 22 May 2011 09:15:30 +0000</pubDate>
		<dc:creator>danbrown</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Webdev]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.etrium.co.uk/?p=258</guid>
		<description><![CDATA[It seems that every website now has at least some AJAX component to it. Whether it is an updating Twitter feed, checking if a username is available or a full-blown web app, they all have one thing in common &#8211; A connection back to a server via an external API. It might return be a [...]]]></description>
			<content:encoded><![CDATA[<p>It seems that every website now has at least some AJAX component to it. Whether it is an updating Twitter feed, checking if a username is available or a full-blown web app, they all have one thing in common &#8211; A connection back to a server via an external API. It might return be a single letter or a 500k XML file but you have a defined way to request and retrieve your data.</p>
<p>But what if that external API gives different results than when you load the page? This is usually a case of duplicated code where only one copy gets changed. We want to make sure that someone loading the page and someone getting an AJAX update always get the exact same data at a given point in time.</p>
<p>There is <a href="http://www.etrium.co.uk/2011/02/27/xmlhttprequest-misuse-on-page-load-with-ajax/">the dumb solution</a> that I have written about before &#8211; not outputting it at all and doing an immediate AJAX update when the page first loads. This post is about a much more correct solution.</p>
<p>The most sensible way is to generate that data via a single function and use it in both places. You want to be defining an internal API where your main site display code and AJAX code are both consumers of it. By doing this you also make sure that your business logic is neatly partitioned away and any changes to it are then reflected throughout. People who use MVC frameworks already do this as a matter of course and their views (display logic) are kept well apart from the models (business logic).<br />
<span id="more-258"></span></p>
<h2>Example</h2>
<p>Lets look at a simple example that we want to AJAXify. We have a page that shows the status of a few servers and want it to update every five minutes. I am only giving snippets of code here, not a full working page and no error checking. The code used is PHP with jQuery but it doesn&#8217;t matter, it applies to ASP.net, Ruby, Perl, ColdFusion, etc just as much. I&#8217;ll use REST for the AJAX calls for simplicity.</p>
<p>First up, the original non-AJAX code -</p>
<p>index.php</p>
<pre>
<pre class="brush: php; title: ; notranslate">
...
&lt;ul class=&quot;server_status&quot;&gt;
  ?&gt;
    // Get statuses
    $query = &quot;SELECT server_name, server_status FROM servers;&quot;
    $result = mysql_query($query);

    while ($server = mysql_fetch_array($result))
    {
      echo '&lt;li&gt;'.$server['server_name']. - '.$server['server_status'].'&lt;/li&gt;';
    }
  &lt;?php
&lt;/ul&gt;
...
</pre>
</pre>
<p>Nice and simple and puts the results in an unordered list, to be styled as the designer sees fit.</p>
<h2>The wrong way to add AJAX</h2>
<p>This is the &#8220;solution&#8221; I mentioned in my previous post. To summarise the three major flaws -</p>
<ol>
<li>An ugly user experience when the page loads in stages.</li>
<li>No graceful degradation &#8211; The site is left with a gaping hole or broken when JavaScript isn&#8217;t available.</li>
<li>The AJAX data is not available to search engine crawlers and so they won&#8217;t index that content.</li>
</ol>
<p>See twitter.com while logged in with a slow connection for a high-profile example of the first one, and with javascript disabled for the second&#8230;</p>
<p>index.php</p>
<pre>
<pre class="brush: php; title: ; notranslate">
...
&lt;ul class=&quot;server_status&quot; id=&quot;server_status&quot;&gt;
&lt;li&gt;Checking server statuses...&lt;/li&gt;
&lt;/ul&gt;
...

&lt;script type='text/javascript'&gt;
  function UpdateServerStatus(result)
  {
    $(&quot;#server_status&quot;).html = result;

    // Get new statuses after 5 minutes
    setTimeout(GetServerStatus, 5*60*1000);
  }

  function GetServerStatus()
  {
    // AJAX call to get new statuses
    $.ajax({url:&quot;get_status_ajax.php&quot;, success: UpdateServerStatus, cache:false});
  }

  $(document).ready(GetServerStatus);
&lt;/script&gt;
</pre>
</pre>
<p>get_status_ajax.php</p>
<pre>
<pre class="brush: php; title: ; notranslate">
&lt;?php
  // Get statuses
  $query = &quot;SELECT server_name, server_status FROM servers;&quot;
  $result = mysql_query($query);

  while ($server = mysql_fetch_array($result))
  {
    echo '&lt;li&gt;'.$server['server_name']. - '.$server['server_status'].'&lt;/li&gt;';
  }
?&gt;
</pre>
</pre>
<p>This code loads an empty status list then does an AJAX call to fill it in and then again every 5 minutes.</p>
<h2>The better way to add AJAX</h2>
<p>A better solution is to wrap any features that will be exposed to both external and internal requests with a function or small API. Then just call it where needed.</p>
<p>index.php</p>
<pre>
<pre class="brush: php; title: ; notranslate">
&lt;?php
  include_once('status_funcs.php');
?&gt;
...
&lt;ul class=&quot;server_status&quot; id=&quot;server_status&quot;&gt;
  &lt;?php echo GetStatus(); ?&gt;
&lt;/ul&gt;
...

&lt;script type='text/javascript'&gt;
  function UpdateServerStatus(result)
  {
    $(&quot;#server_status&quot;).html = result;

    // Get new statuses after 5 minutes
    setTimeout(GetServerStatus, 5*60*1000);
  }

  function GetServerStatus()
  {
    // AJAX call to get new statuses
    $.ajax({url:&quot;get_status_ajax.php&quot;, success: UpdateServerStatus, cache:false});
  }

  function StartUp()
  {
    setTimeout(GetServerStatus, 5*60*1000);
  }

  $(document).ready(StartUp);
&lt;/script&gt;
</pre>
</pre>
<p>get_status_ajax.php</p>
<pre>
<pre class="brush: php; title: ; notranslate">
&lt;?php
  include_once('status_funcs.php');

  echo GetStatus();
?&gt;
</pre>
</pre>
<p>status_funcs.php</p>
<pre>
<pre class="brush: php; title: ; notranslate">
&lt;?php
  function GetStatus()
  {
    $status = &quot;&quot;;

    // Get statuses
    $query = &quot;SELECT server_name, server_status FROM servers;&quot;
    $result = mysql_query($query);

    while ($server = mysql_fetch_array($result))
    {
      $status .= echo '&lt;li&gt;'.$server['server_name']. - '.$server['server_status'].'&lt;/li&gt;';
    }

    return $status;
  }
?&gt;
</pre>
</pre>
<p>Now the page is filled in at page load so it will give the right info without any updating at all. No extra initial AJAX call either so a win-win situation.</p>
<p>I am returning an HTML string which is fine for such a simple feature that only this site uses. For more complicated things or public APIS it&#8217;s probably better to return an array from the function instead then convert and pass it via JSON (for AJAX) or directly (for your initial page load). The processing would be duplicated between server-side language and the javascript, but it adds the flexibility that you (and more importantly your API consumers) need. Don&#8217;t be tempted to just pass a JSON string at page load and fill it in via Javascript. You regain points 2 and 3 of the bad solution by doing that.</p>
<h2>End</h2>
<p>It&#8217;s minimal extra code. Both new versions use the same AJAX and timing code so that can be ignored in a comparison. By adding one function you get a much more solid experience for the user. Also you don&#8217;t run the risk of updating one version of the code and not the other giving an inconsistent status. This is especially handy when more than one person is working on the code as the one doing output code can treat the internal API as a black box and not have to look inside it to see what it is doing.</p>
<p>There are occasional reasons that things need to be loaded after the initial page load such as if the browser properties (dimensions, capabilities, etc) are vital. I used Google Maps in my example on the earlier post although even there a small map could be pre-loaded to get it up and running as fast as possible while it loads the parts around it.</p>
<p>Is there any sane reason not to do it this way?<br />
Is there a better way still?</p>
<p>Let us all in on the secret in the comments!</p>

]]></content:encoded>
			<wfw:commentRss>http://www.etrium.co.uk/2011/05/22/the-right-way-to-add-ajax-support-to-your-site/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The evils of premature optimisation</title>
		<link>http://www.etrium.co.uk/2011/03/23/the-evils-of-premature-optimisation/</link>
		<comments>http://www.etrium.co.uk/2011/03/23/the-evils-of-premature-optimisation/#comments</comments>
		<pubDate>Wed, 23 Mar 2011 22:25:05 +0000</pubDate>
		<dc:creator>danbrown</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Optimisation]]></category>
		<category><![CDATA[Premature]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://www.etrium.co.uk/?p=228</guid>
		<description><![CDATA[Image via Jens Christoffersen on Flickr It is always tempting to try and speed up the bit of code you just wrote. Sometimes it is tempting to try and speed up code you haven&#8217;t even started yet by over-thinking the algorithm. Unless your codebase is functionally complete or the code is so slow and/or resource [...]]]></description>
			<content:encoded><![CDATA[<div style="text-align: center; margin: 0 0 40px 0;"><img style="margin-top: 20px; margin-bottom: 20px;" title="Optimised" src="http://farm2.static.flickr.com/1254/1361108717_20fae24bef_z.jpg" alt="A pimped car" /><br />
Image via <a href="http://www.flickr.com/photos/nsop/1361108717/">Jens Christoffersen</a> on Flickr</div>
<p>It is always tempting to try and speed up the bit of code you just wrote. Sometimes it is tempting to try and speed up code you haven&#8217;t even started yet by over-thinking the algorithm.</p>
<p>Unless your codebase is functionally complete or the code is so slow and/or resource hungry that it stops things from working, it is too early to optimise it beyond what is absolutely necessary.<br />
<span id="more-228"></span></p>
<h2>Get it done</h2>
<p>Optimising takes time, sometimes significant amounts of it.</p>
<p>In the majority of situations it will be better to get 10 features complete and slow/inefficient, than a single feature running perfectly. Once everything works, go back and optimise things that actually need to be fast.</p>
<p>With <a href="http://www.moagallery.net">Moa</a> we recently added a new major feature that meant we had to re-index potentially thousands of images if somebody changed a gallery. It is easy to do but took 15 seconds for 400 images as it performed one query per image. We left it as it was and carried on to implement the rest of the feature in other files. Once it worked everywhere we went back and made it fast. We still didn&#8217;t do it the ideal way (we just turned on transactions for the duration of the re-index) although it now only takes a fraction of a second so it is fast enough.</p>
<h2>Direction change</h2>
<p>Until you have the whole system there to use, you don&#8217;t always know if you have the right approach or if what you have done will even be in the end product. Features get cut to make release dates or because they were great on paper but suck in reality. Better to throw away a few hours rough work than an optimised version that took days.</p>
<p>Sometimes (or often in some industries)  the requirements change halfway through a project and you have to throw things out. Nobody likes deleting code but it is better than leaving it unused to rot. You can always get it back from version control later if you reverse course again.</p>
<p>Ideally you would have a design signed off and things won&#8217;t change. Easier for agencies and freelancers to stick to, hard for corporate programming in a non-IT field.</p>
<h2>Not just code</h2>
<p>Algorithms are not the only place that can benefit from optimisation or be hurt by doing it prematurely. It is common for game developers to use machines that are vastly more powerful than the target hardware. This is a relatively cheap way to get all the features in place and still have a playable game. Once that is done and the content creators can start to do their thing, the coders get to work on the optimisation to target real hardware.</p>
<p>It might be that the project needs to be assessed once it reaches a usable state to see if it is even worth continuing. You want that done as early as possible to avoid wasting time.</p>
<p>When the PC game Quake was being developed, <a href="http://www.idsoftware.com">id Software</a> chose to write it on NeXTStep workstations so they could run the game, the editor and other tools side-by-side and with more CPU power (four processors) than a PC. This let the artists and designers get on with doing their jobs and testing real content in-game without the limitations of a PC at the time. At that point they were the most important people to need it running. A nice non-code early optimisation to boost productivity.</p>
<p>Optimisation can also apply to just about anything so this is a general life tip too! I spent hours one weekend working out a route to travel from Bangkok, Thailand down through Indonesia and Malaysia, ending up at Darwin in north-west Australia. A few days later we changed our plans and decided to go to Japan instead so I lost all that time due to premature optimisation&#8230; It was fun working it out and I hope to do the trip someday but I would have been in trouble if my time was accountable to bosses and/or clients.<sup>[<a href="#footnote" class="footnoted" id="to-footnote">1</a>]</sup>.</p>
<h2>When is it OK?</h2>
<p>There are times you do need to optimise early. If the inefficiency stops the system being useful at all then it is worth optimising at least partially to get it working well enough to get on with more features.</p>
<p>I had a project once where I could only use Microsoft Access and Visual Basic for Applications. It was a 300Mb dataset that our clients had exported from MS SQL Server with tables of over 200,000 rows saved in mdb format. Some of the search queries I wrote would take several minutes to run, not good enough for what we needed it for and it was only going to get more complicated in the future.</p>
<p>We were only going to get updated datasets a couple of times a year so I decided I would optimise it by precalculating a lot of the stuff that it had to work out each time. The precalculation took 8 hours to run, but then searches took under a second. Well worth doing and we left it at that. 3 years later I had to do some updates to the code so I optimised the precalc properly and it down to around 20 minutes.</p>
<p>Another example would be if the brute-force version of an algorithm would use more memory than you had in the computer. Going back to Quake again, id used a precalculated PVS (potentially visible set) to save the PC having to calculate what should be drawn from a given location. It used too much of memory though, &#8220;several&#8221; Mbytes. They RLE compressed it and got it down to about 20kb instead.</p>
<h2>Conclusion</h2>
<p>The main thing to take away is to make sure you are doing the right thing before you spend time making it perfect.</p>
<p>In general, fully optimise if -</p>
<ul>
<li>There are no more major features to add.</li>
<li>You know the feature is staying.</li>
<li>You know (using real measurements) that the feature is causing a problem by not being efficient.</li>
<li>The increased efficiency is needed right now.</li>
</ul>
<p>Do you know any other reasons to optimise early? Or maybe a tale of when it has bitten you in the ass to? Let us know below!</p>

<ol class="footnotes">
	<li class="footnote" id="footnote"><strong><sup>[1]</sup></strong> Off-topic side note. Don&#8217;t micro-manage your travel plans in advance! I  do enough to know what there is to see in the region, how the travel  infrastructure works and what is needed for border crossings in the way  of visas, currency, etc. I&#8217;ve made this mistake before and nothing sucks  as much as arriving somewhere amazing and knowing that you only have a  few hours before your next bus or train. It can also be very tiring  trying to fit too much in. Better to see one thing properly than two or  three things on rushed visit. The other stuff will usually still be  there later.so you have a good excuse to go back. <a class="note-return" href="#to-footnote">&#x21A9;</a></li></ol>
]]></content:encoded>
			<wfw:commentRss>http://www.etrium.co.uk/2011/03/23/the-evils-of-premature-optimisation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery, confusing sample code and elegance</title>
		<link>http://www.etrium.co.uk/2011/03/13/jquery-confusing-sample-code-and-elegance/</link>
		<comments>http://www.etrium.co.uk/2011/03/13/jquery-confusing-sample-code-and-elegance/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 23:37:07 +0000</pubDate>
		<dc:creator>danbrown</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Webdev]]></category>
		<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://www.etrium.co.uk/?p=160</guid>
		<description><![CDATA[Image via Andrew Dupont on flickr Have you ever found a cool snippet of code that does almost what you need, tried to tweak it but it is formatted in such a way that you can&#8217;t work out what the hell it is doing? I&#8217;ve noticed this so often recently I thought I&#8217;d try and [...]]]></description>
			<content:encoded><![CDATA[<div style="text-align: center; margin: 0 0 40px 0;"><img style="margin-top: 20px; margin-bottom: 20px;" title="Javascript" src="http://farm1.static.flickr.com/51/113966179_21836ae41d.jpg" alt="Picture of JavaScript Code" width="241" height="241" /><br />
Image via <a href="http://www.flickr.com/photos/savetheclocktower/113966179/">Andrew Dupont</a> on flickr</div>
<p>Have you ever found a cool snippet of code that does almost what you need, tried to tweak it but it is formatted in such a way that you can&#8217;t work out what the hell it is doing?</p>
<p>I&#8217;ve noticed this so often recently I thought I&#8217;d try and steer people back onto the sanity bandwagon.</p>
<p>Part of writing elegant code is to make it both understandable and easier to debug, re-use and maintain.</p>
<p>The following is a JavaScript example although it can effect any language.<br />
<span id="more-160"></span></p>
<h2>Example</h2>
<p>I found the following <a href="http://jquery.com/">jQuery</a> code while looking for a 10-20 line example to work with (source -  <a href="http://tympanus.net/codrops/2010/04/29/awesome-bubble-navigation-with-jquery/">Awesome bubble navigation with jQuery</a>). The sample provides circles with words in and when you mouse over them they grow like bubbles to contain a contextual menu for that word.</p>
<p><strong>note.</strong><br />
The actual code is fine and does what it is supposed to.  It is only the obfuscated layout that I am talking about here and even this isn&#8217;t too severe.  I certainly don&#8217;t want to pick on the author.  It is also a very nice effect and probably useful to a lot of people.  She has a lot of other shiny jQuery stuff on <a href="http://tympanus.net/codrops/author/crnacura/">that site</a> so go take a look!</p>
<pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;&gt;
  $(function() {
    $('#nav &gt; div').hover(
    function () {
      var $this = $(this);
      $this.find('img').stop().animate({
        'width'     :'199px',
        'height'    :'199px',
        'top'       :'-25px',
        'left'      :'-25px',
        'opacity'   :'1.0'
      },500,'easeOutBack',function(){
        $(this).parent().find('ul').fadeIn(700);
      });

      $this.find('a:first,h2').addClass('active');
    },
    function () {
      var $this = $(this);
      $this.find('ul').fadeOut(500);
      $this.find('img').stop().animate({
        'width'     :'52px',
        'height'    :'52px',
        'top'       :'0px',
        'left'      :'0px',
        'opacity'   :'0.1'
      },5000,'easeOutBack');

      $this.find('a:first,h2').removeClass('active');
    }
  );
  });
&lt;/script&gt;
</pre>
<p>You can work out how it works but you shouldn&#8217;t have to. It should tell you.</p>
<p>Looking once or twice isn&#8217;t going to be too much of a hassle. Working on code for a few hours though and you will want something more.</p>
<p>It isn&#8217;t immediately obvious for example that the two big anonymous functions in there are actually parameters to the same function. Adding comments would have made it worse rather than helping. Also changing some of the values for timing involves having to search for them.</p>
<p>By splitting the anonymous functions into named functions and the values into variables it becomes far more obvious what is going on -</p>
<pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;&gt;
  var hoverState = {'width'     :'199px',
                 'height'    :'199px',
                 'top'       :'-25px',
                 'left'      :'-25px',
                 'opacity'   :'1.0'};

  var unHoverState = {'width'     :'52px',
                     'height'    :'52px',
                     'top'       :'0px',
                     'left'      :'0px',
                     'opacity'   :'0.1'};

  var fadeInTime = 700;
  var fadeOutTime = 500;
  var growTime = 500;
  var shrinkTime = 5000;

  function FadeInMenu()
  {
    $(this).parent()
           .find('ul')
           .fadeIn(fadeInTime);
  }

  function HoverStart()
  {
    var $this = $(this);

    $this.find('img')
         .stop()
         .animate(hoverState, growTime, 'easeOutBack', FadeInMenu);

    $this.find('a:first,h2')
         .addClass('active');
  }

  function HoverEnd()
  {
    var $this = $(this);

    $this.find('ul')
         .fadeOut(fadeOutTime);

    $this.find('img')
         .stop()
         .animate(unHoverState, shrinkTime, 'easeOutBack');

    $this.find('a:first,h2')
         .removeClass('active');
  }

  function AddEvents()
  {
    $('#nav &gt; div').hover(HoverStart, HoverEnd);
  }

  $(document).ready(AddEvents);
&lt;/script&gt;
</pre>
<p>The timings and size settings can now be very easily tweaked in one place, the code flow is more obvious and how it effects the DOM is much clearer. I have expanded the final line from the jQuery &#8220;document ready&#8221; shorthand to show the intent clearer.</p>
<p>The AddEvents function isn&#8217;t strictly necessary here as there is only one event, but as there is often more than one thing on a page it sets it up nicely for that. If you add another event for something else you want to avoid the temptation to just jam it in an anonymous function on the document ready part.</p>
<h2>Why bother?</h2>
<p>So you aren&#8217;t writing code to be seen and as long as it works, why should you care?</p>
<p>If you can write that first version of the code perfectly first time with no typos, bugs, or missing brackets, and nobody will need to ever edit it again then fine, go for it. If you are like the other 99.9% of us however it will make your life easier.</p>
<ul>
<li>You can find and tweak the parameters without having to care how code itself works.</li>
</ul>
<ul>
<li> You can develop and test the functions in isolation rather than the entire thing in one go.</li>
</ul>
<ul>
<li> You can spend less time debugging.</li>
</ul>
<ul>
<li> You can change it more easily to match any changed HTML structure.</li>
</ul>
<ul>
<li> You can reuse functions in other variations or different effects on the same page.</li>
</ul>
<ul>
<li> You can put the functions in a .js file and reuse the entire effect on other pages.</li>
</ul>
<ul>
<li> You can share it with friends, colleagues or on your site itself and expect they will be able to understand what is going on.</li>
</ul>
<ul>
<li> You can add comments for either while you are developing or for when you come back at a later date.</li>
</ul>
<ul>
<li> You can let other people see your code without embarrassment. e.g job interviews!</li>
</ul>
<ul>
<li> You can develop much more complicated effects and still have a chance to keep things straight in your head.</li>
</ul>
<h2>Size</h2>
<p>The new version is longer than the old one (1267 bytes vs. 839) and would be longer still with comments.</p>
<p>This is quite often the case with making things readable. However I don&#8217;t consider it an issue. Unless you go completely overboard with the comments&#8230;</p>
<p>The other JavaScript files (jQuery and the easing add-on) are over 37k alone and the whole (simple) demo page is 148.9k. A few extra kilobytes for the benefits it gives is a fantastic tradeoff. Moving the functions to a separate .js file would let the browser cache it anyway. A lot of the extra size is spaces for indenting so you can always minify it or use tabs (bleugh!) to save even more.</p>
<h2>Conclusion</h2>
<p>Anonymous functions are not evil. But they have a place, and &#8220;everywhere you can jam one in&#8221; isn&#8217;t it!</p>
<p>I think part of the problem is that the jQuery API reference uses them for single line demos. The more new programmers see code written that way, the more they will think it is the correct way.</p>
<p>If you don&#8217;t already do this, give it a try the next time you write something and see if it speeds up your coding. You have nothing to lose and everything to gain. Let me know in the comments below how it goes!</p>

]]></content:encoded>
			<wfw:commentRss>http://www.etrium.co.uk/2011/03/13/jquery-confusing-sample-code-and-elegance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XMLHttpRequest Misuse on Page Load with AJAX</title>
		<link>http://www.etrium.co.uk/2011/02/27/xmlhttprequest-misuse-on-page-load-with-ajax/</link>
		<comments>http://www.etrium.co.uk/2011/02/27/xmlhttprequest-misuse-on-page-load-with-ajax/#comments</comments>
		<pubDate>Sun, 27 Feb 2011 00:34:44 +0000</pubDate>
		<dc:creator>danbrown</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Webdev]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[MiniRant]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[XMLHttpRequest]]></category>

		<guid isPermaLink="false">http://www.etrium.co.uk/?p=124</guid>
		<description><![CDATA[Introduction XMLHttpRequest is a JavaScript function that allows the core dynamic data part of AJAX (Asynchronous JavaScript And XML) to work. It lets JavaScript running in a web browser call a URL on the same server and receive data back again to process. Either normal HTML, XML or any format such as JSON can be [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>XMLHttpRequest is a JavaScript function that allows the core dynamic data part of AJAX (Asynchronous JavaScript And XML) to work. It lets JavaScript running in a web browser call a URL on the same server and receive data back again to process. Either normal HTML, XML or any format such as JSON can be returned and the JavaScript can do what it likes with it. This lets the page update itself or submit a form without making the whole page refresh which typically gives the user a much better experience. Obvious examples are a news website with up-to-date news &#8216;ticker&#8217;-style headlines or live sports commentary, Viewing more comments in YouTube, Search engine pop-up suggestions as you type, and so on.</p>
<p><span id="more-124"></span></p>
<h2>The Misuse</h2>
<blockquote><p>&#8220;When you have a shiny new hammer, every problem looks like a nail.&#8221;</p></blockquote>
<p>As a way to update a page or get new data according to user actions or a timer this is incredibly powerful. But I see so many sites using it as a way to fill in the initial content <em>during</em> the initial page load. Apart from slowing down the overall page load itself by making additional requests to the server, it gives a jarring wait when it looks like it should have finished but then goes on to display &#8216;Loading&#8230;&#8217; or worse, nothing. I am not writing this to give a flashy solution, it should be obvious for developers. I wrote it to raise awareness that it is a problem.</p>
<p>As an example, and not picking on him in any way, Ben Marsh made a hit website last year that became very popular during this winters snow and I&#8217;m sure will again in the future &#8211; <a href="http://uksnow.benmarsh.co.uk/">http://uksnow.benmarsh.co.uk/</a>. As a social content aggregator and public service it worked fantastically and I spent a large amount of time there myself watching the weather move around the UK. But watch what happens when you load/refresh the page&#8230; The main part loads, the Google Maps interface comes up and the tweet panel sits there empty with a message at the top saying &#8216;Updating tweets&#8217;&#8230; He had to cache the messages on his server to avoid the twitter API locking him out so it is all stored there to use. So why are we waiting? The data can&#8217;t have changed significantly in the few seconds since the page loaded so why isn&#8217;t the list pre-populated as part of the page load itself? It makes the page extremely slow to load, especially when the server load was very high in the worst of the cold spell.</p>
<p>A worst-case example was a mapping component I saw on an internal government department website. In IE8 and Firefox it cached things and worked reasonably but in IE6, which we are forced to use at work, it reloaded every icon and menu item multiple times (over a thousand requests for a single refresh) after the page load. It sometimes took a full minute to bring the map system up fully&#8230; This wasn&#8217;t even dynamic content! The map part worked fine once it was working, it was the map layer menu and fixed icons that it was reloading which would have stayed the same for months at a time. It was live for about a week before they had so many complaints that they had to go back to the old ActiveX version which they still use six months later. They also have a site main menu that loads via AJAX after the page load and a few forms that reload several seconds after the page has loaded, resetting the focus and making me type into nothing until I notice half a blank sentence later.</p>
<h2>Why it happens</h2>
<p>The reason for this, I believe, is a misguided attempt to avoid duplicate code &#8211; One block for the AJAX handler and another almost identical on the page load. As developers it is easy to look for ways to re-use code (or just avoid re-writing it again), put two and two together and decide to use the AJAX version for both purposes. Running on a local unstressed web server it is pretty responsive and people may either not test it remotely or work in a company where the production server is also local. This means they never notice how slow and/or visually odd it is for real world users.</p>
<p>Another reason that this may sadly become more common is Googles recent announcement that they may take page load time into account for rankings. Some web spiders (although not Googles I believe) don&#8217;t do JavaScript and so will see the empty page as the full load time. Misusing XMLHttpRequest this way will let them get a better &#8216;score&#8217; on some phrase if that search engine adopts the time measurement also.</p>
<p>This does cause another  SEO problem with bots that can&#8217;t follow AJAX requests &#8211; If the initial data never gets loaded, it can&#8217;t be indexed. So no free secondary &#8216;splash&#8217; search engine ranking when a phrase matches something in their content. Plenty of non-techy website owners that use cheap outsourcing facilities would put page rank on a specific page/phrase above this other method of getting free incoming traffic as they simply don&#8217;t know about it. The 2nd world ultra-low budget bulk outsourcing firms aren&#8217;t going to care which method they use if they can claim to boost pagerank.</p>
<h2>How to avoid</h2>
<p>Very easily -</p>
<p>Make both your AJAX handler and the main page generating code call a common function which generates the content. Tada! &#8211; code reuse and faster, smooth page loads for users.</p>
<p>Your page size will go up. That is saved by not having to do a second server request so it actually ends up about the same bandwidth used apart from in one case &#8211; If your original page can be cached. It&#8217;s up to you if the slight bandwidth saving is worth giving your users/customers a worse experience for. If you have an e-commerce site you should already know how fickle a large percentage of customers can be and a very slow page load can be a good enough reason for them to leave your site and go to the next one the search engine suggests.</p>
<h2>Conclusion</h2>
<p>Test your sites remotely on a stressed server to see it the same way a user does.</p>
<p>There are valid reasons to use XMLHttpRequest this way, mainly if the user expects it not to be instant anyway. Google Maps is a good reason to load content just after the page load as it can&#8217;t tell browser dimensions until then.</p>
<p>Are there any others? Have you noticed this as a problem as well or do you think it isn&#8217;t worth worrying about?</p>
<p>Leave feedback in the comments if you want.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.etrium.co.uk/2011/02/27/xmlhttprequest-misuse-on-page-load-with-ajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>#include &#8220;blog&#8221;</title>
		<link>http://www.etrium.co.uk/2011/02/06/begin/</link>
		<comments>http://www.etrium.co.uk/2011/02/06/begin/#comments</comments>
		<pubDate>Sun, 06 Feb 2011 13:57:22 +0000</pubDate>
		<dc:creator>danbrown</dc:creator>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[about]]></category>

		<guid isPermaLink="false">http://www.etrium.co.uk/?p=1</guid>
		<description><![CDATA[An introduction to the blog]]></description>
			<content:encoded><![CDATA[<p>I thought it was about time I started a real blog and so here we are.</p>
<p>I do write on blogs for two projects I work on, however both are fairly specific so I wanted one I can ramble on about anything I am interested in or up to. There theme of the blog is mostly programming, technology and general geekery. I&#8217;ll list each of my interests below. there is always a possibility that I might do an out-of-theme post once in a while -</p>
<p><span id="more-1"></span></p>
<h3>Programming</h3>
<p>Nowadays I mostly use PHP, JavaScript and occasionally microcontroller assembly for hobbies, but I also like to keep my toe dipped into the C/C++ pond and have VBA inflicted upon me at work sometimes. I like to think I am keeping up with coding standards and methodologies however you wouldn&#8217;t know that from reading my code&#8230;</p>
<p>I run two small open source projects, one active (<a title="Moa" href="http://www.moagallery.net/">Moa</a>, a web-based image gallery) and one currently inactive but still used (<a title="Titan" href="http://titan.sourceforge.net/">Titan</a>, a C++ image loading/saving library). I am working on a third at weekends &#8211; a raid DKP tracking system for World of Warcraft, no link yet. And a fourth hopefully launched before the end of the year for a web-based astronomy observation log.</p>
<p>I have always wanted to write games, though other things always get in the way. So no surprise I have one of those in development as well. Only a simple asteroids clone but with a few extras thrown in for good measure. It has been on hold for over a year now due to concentrating on Moa.</p>
<h3>Digital Electronics</h3>
<p>I mean making devices, not buying them. Modern microcontrollers such as the Microchip PIC and some experience of low-level assembler from my early PC days made this a fairly easy transition from PC programming.</p>
<p>I have two projects so far in this field. First is a camera intervalometer that triggers a camera via infra-red at a set frequency to make time-lapse video (<a title="Time-lapse video on YouTube" href="http://www.youtube.com/watch?v=Ab5Rq_dpZUw">link</a> to my first test). Second is a device I made for my telescope to enable auto-guiding (working) and periodic error correction (semi-working) on my telescope mount with a webcam. I need to rewrite the software for the latter project when I am able to get the scope out again.</p>
<p>I couldn&#8217;t do analogue electronics to save my life.</p>
<h3>Photography</h3>
<p>I got into this as I wanted to do astro-photography. I bought an old film Olympus OM10 SLR camera but ended up using it more for regular pictures than astronomy ones. I upgraded to an Olympus C-5050 Zoom digital compact soon afterwards and now use a Nikon D60 digital SLR. I make no claims to being any good at photography and I have a lot to learn still, but I enjoy it and do get some good pics occasionally. My personal gallery (using Moa) is <a title="My photo gallery" href="http://www.etrium.co.uk/photo/">here</a>.</p>
<h3>Astronomy</h3>
<p>I took a course at the <a title="Open University" href="http://www.open.ac.uk/">Open University</a> a few years back in Planetary Science and bought a cheap 30mm refractor from Cash Convertors as I thought it might help. I enjoyed looking at the night sky and trying to find those faint fuzzy galaxies/nebulae so much a few months later I splashed out and got a 6 inch reflector. A 9am start at work with bad weather and heavy light pollution due to living in an estate play havoc with being able to use it often now though. I should be moving in a couple of months though and a ground floor flat with dark(ish) garden will be high on my list of requirements. I use a webcam to take pictures now, being far more convenient than an SLR. It is low-resolution and grainy, but I get some OK pics considering its those limitations (<a title="my astro pics" href="http://www.harthinian.com/astro/images.html">gallery</a>).</p>
<h3>Gaming</h3>
<p>You think I have time left over to play games as well! Well, OK I do but not as often as I&#8217;d like. When I get time I like to play the old classics that blow a lot of todays games out of the water &#8211; XCOM and Terror From the Deep, Thief, Final Fantasy 7-9, Elite, Civilisation, Wizball, Head Over Heels, Sim City and sometimes even The Sims. Two new games I am looking forward to when they are eventually released are Thief 4 and Half Life 2: Episode 3.</p>
<p>I would also like to get into paper and pen role playing games, however convincing friends that they want to as well is harder than I thought it would be. I&#8217;ve never played D&amp;D but would like to try. I have played both Heroes Unlimited and Call of Cthulhu and would happily play both again regularly. I am still surprised with things like Skype, Social Media and much more Internet-savvy people around that there isn&#8217;t a app to do this and let people find other like-minded players rather than being pre-arranged amongst friends. There is one simple one I found but was very dated and clunky to use. Maybe I should launch a fifth open source project as well&#8230;</p>
<h3>Technology</h3>
<p>I like trying new things, within the range of my wallet at least. And so when possible I try new software and hardware to see how things work. I try not to follow the crowd, not out of stubborness but because someone else will always get it and I can have a play with theirs instead. One thing seems to be universal though &#8211; Manufacturers are appear to be very ignorant of what people will actually be doing with their device/software and the usability suffers a lot.</p>
<p>I use Linux as my desktop OS. I do have windows 7 and stupidly paid full price for it. I only boot into that a few times each month though, mosly for gaming. Linux can be frustrating and still isn&#8217;t quite right for mainstream use yet in my opinion. More about that to come in a post though.</p>
<h3>Fiction (mainly Science Fiction and Horror)</h3>
<p>I like to read hard sci-fi and get both <a title="Analog magazine" href="http://www.analogsf.com/index.html">Analog</a> and <a title="Asimovs magazine" href="http://www.asimovs.com/index.shtml">Asimovs</a> magazine most months. Novels as well of course and I am currently re-reading Red Mars by Kim Stanley Robinson. Most TV and movies are soft-sci-fi though and rightly so or their ratings would plummet. They do tend to end up getting trapped in formulaic ruts or using the sci-fi technology as a replacement for a good plot though. Some of the supposedly geek fan-favourite sci-fi/fantasy classics I couldn&#8217;t stand though, Enders Game particularly, also Dune and Snow Crash.</p>
<p>Horror I like also, although a good modern horror novel seems hard to find now. Back in school during the 80&#8242;s it was great with James Herbert, Shaun Hutson, Steven King, etc bringing new books out fairly regulary. So I tend to re-read those or go further back in time to the great grand-daddies of them all &#8211; HP Lovecraft and Edgar Allen Poe.</p>
<p>I do read other genres as well. I like the Harry Potter series even though I generally don&#8217;t like fantasy. The Beach, Fight Club, On the Road, Fear and Loathing in Las Vegas, etc are all great books. One plot-type that I especially like, regardless of genre, is the castaway. Not sure why but it seems to be a recurring theme in some of my favourite books/movies.</p>
<h3>Science Fact</h3>
<p>I learn for pleasure. Always have done and so perhaps it isn&#8217;t surprising that I have taken a few courses and try and keep up to date in stuff I want to know more about. So far with the Open University I have done courses in Planetary Science, Oceanography, Geology, Optics and Artificial Intelligence. Not for any reason or qualification, just to know more about the subject.</p>
<h3>Travel</h3>
<p>Something I wish I had the opportunity to do more often. My last few holidays have been to Thailand and Japan (twice each), Barcelona and Eastern Europe. All have been with backpacks staying in hostels and guest houses and I wouldn&#8217;t trade them for a hotel/resort holiday for anything. For me the purpose of the holiday is to see other countries/cultures not just get a tan, get drunk and come home with some souvenirs.</p>
<p>I am currently planning and saving  for a 5-6 month trip around the world probably to be taken in the summer of 2012. None of this &#8216;fly around the world stopping in 3-4 countries and say you have travelled around the world&#8217; crap either.  Over land/sea from the UK through Europe, across Russia, Mongolia and into China, down through southeastern Asia to Australia. Then New Zealand over to South America and up by bus into the US and across to the east coast. It does involve four flights I can&#8217;t really avoid though &#8211; Bali-&gt;Darwin, Sydney-&gt;Christchurch, Auckland-&gt;Santiago and Boston-&gt;Glasgow but I worked out the land-based travel is in-excess of 30000 miles, 10000 more for the flights. I did hope to do it last year but work issues mean it would be better put off for now. Not sure what I&#8217;ll be doing this year. Friends are keen to go on a canal boat in the UK for a few weeks which sounds ok.</p>
<h3>About me</h3>
<p>Not a subject I will write about, but for info.</p>
<p>I am 34, male and live near Aldershot in the UK. I work for a geotechnical department of a global company in Woking doing none of the above although occasionally get to do some Visual Basic coding within Microsoft Access.</p>
<p><em>Dan Brown (no, not that one)</em></p>

]]></content:encoded>
			<wfw:commentRss>http://www.etrium.co.uk/2011/02/06/begin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

