Archive for the ‘javascript’ Category

YUI After the Dojo Snail

March 7th, 2007

I remember seeing Dojo for the first time and I was hooked on the flashy gizmo’s and widgets from the off. The awkward learning curve was cast aside as I went about reading and listening to everything I could lay my hands on. After a while of using Dojo on many of my work projects one of Dojo’s most common complaints became apparent – Speed!
Now this wasn’t because of using excessive amounts of Ajax in inappropriate places. One page in particular just had two dialogs but was very slow to load and would struggle to run on anything at standard ‘business level’ workstations.After some digging I found a number of different ways in which you can improve the speed of Dojo so I set about each one with varying degrees of success.

Implement Using Javascript – Most people when they hit Dojo and get onto all the fancy widgets go straight for the parsed widgets where Dojo simply parses the document for any Dojo tags and generates the corresponding widget for it. This makes the whole process incredibly simple and quick to develop but ultimately it slows everything down when Dojo is having to re-read the page each time. So using the createWidget method and turning off Dojo parsing the page

Only Include What You Need – Too often people will end up adding a lot of includes they just don’t need for all of their pages all of the time. Trim these down if they’re not needed and reduce the clutter of downloading too much.

dojo.io.bind – Any data you can save from being loaded immediately onto the page can be loaded later using bind. Doesn’t sound like it’d help but I shaved seconds off loading times by lazy loading different parts of the page rather than having large swathes hidden.

However, even after these and a few more little optimisations I was getting fed up. Dojo was SLOW! It was annoying my users and I don’t like them being pissed off if I can help it.

Needing a Fast Data Table
I needed a good data table. One that allowed for pagination, dynamic data, effective sorting, Ajax loading/updating, etc. The Dojo tables (FilteringTable and SortableTable) were miserable attempts at this. Two of mybiggest complaints were 1) Sorting across pages was poorly supported. 2) Dynamic data loading and updating was sketchy at best. 3) SPEED!
Fed up I went looked at a couple of other libraries for a solid well-rounded feel – MochiKit, Prototype/Scriptaculous, YUI, etc. The table was either non-existent or a poor after thought to the library. Considering the huge prevalence of tabled data – certainly in my industry (financial). I find it amazing that a simple, powerful, robust and fast implementation has taken so long to come about. The current libraries seem obsessed with creating fanciful widgets rather than going for something nuts & bolts useful to a huge range of people.

YUI
That was until I caught the YUI DataTable widget. Its only in beta but I’ve been so enthralled with its richness, speed and elegance I’ve begun the process of converting a variety of my table designs at work into this new table. Its stable, robust, fast, feature-packed – you really couldn’t ask for more. Oh – and as usual the Yahoo team have absolutely fantastic documentation.
Well after falling for the YUI DataTable I decided to take a peek at all the other library features I’d given a cursory glance over when I first got into Ajax. It has certainly matured and filled out a lot and after using Yahoo partially in one of my latest work projects I noticed a significant speed boost. So it got me thinking – is the Yahoo UI library faster than Dojo. I’ve been running a few speed tests and looking at the Javascript import speed alone – YUI is streets ahead.

In function calls my Firebug window is filled and scrolled massively from Dojo function calls across multiple files from including simply a DropDownDatePicker into the page. If I do the same with YUI (Calendar) I get a fraction of that activity.

With Dojo I’ve had to wait seconds for a page to load – in YUI its given back the users time and resulted in just as good a product.

I’m going to start shifting all of my Ajax code to YUI over the next few months – thats how good I’ve found YUI to be. I’ll still be using Dojo for some widgets not available in YUI but I’ll be predominantly using YUI from now on.

YUI: Refresh DataTable – Method 2

March 1st, 2007

As mentioned in the previous post the way I refreshed a datatable widget after a change in the data was to reinstantiate the table. The way I did this was to simply make my widgets configuration and creation into a functin which I could then call at will whenever I needed it to take on new data.

However, a new method has sprang up that seems much better. Although slightly less intuitive. There’s a method called

myDataTable.getRecordSet().replace(newData);  // replaces the data with the newest set
myDataTable.paginateRows();  // re-paginates the table
myDataTable.showPage(0);  // shows first page

This also executes marginally faster than rebuilding the entire table.

Yahoo UI – New DataTable Widget

February 27th, 2007

When I first looked at YUI when I was on the hunt for a simple yet powerful Ajax library I cast it aside in favour of Dojo. Which back then I preffered due to its tag parsing as opposed to pure JS implementation of its various widgets.

However, now I’m getting a bit more into the JS side and it doesn’t feel so daunting I decided to take another look at YUI – and I’m very glad I did. Because since my last foray into this Ajax library they’ve added some interesting new features and widgets (in beta stage).

The one I’ve found to be most useful so far has to be the DataTable. Of all the Ajax tables and grids out there that I’ve seen none come close to Yahoo’s DataTable in its speed (happy to deal with 00000’s of records), efficiency, power and functionality. Pagination, sorting, row number, infinite scrolling of data, inline editing, nested columns, row selection, data sources (accepts JSON, XML & CSV) are all very flexible allowing for an immensely powerful widget that puts Dojo’s table to shame.

After some minor niggles I managed to get my YUI DataTable up & running (with the help of Jenny and Nate at the YUI dev list). My cut down example is here in case anyone needs just another example to make something click.

This was decalred in a seperate JS file (as were all my tables) which was then included in the page.

var itemDataTable;
function exec_item_table(id){
var itemColumnHeaders = [
{key:“item_id”, text:“ID”, sortable:true, type:“number”},
{key:“code”, text:“Code”, sortable:true},
{key:“name”, text:“Name”, sortable:true},
{key:“description”, text:“Desc”, sortable:true},
{key:“qty”, text:“Quantity”, sortable:true},
{key:“unit_cost”, text:“Unit Cost”, sortable:true}
];

var itemColumnSet = new YAHOO.widget.ColumnSet(itemColumnHeaders);

// Point to a local or proxy URL
var itemDataSource = new YAHOO.util.DataSource(“http://localhost/bms/bms_ajax.php”);

// Set the responseType as TEXT
itemDataSource.responseType = YAHOO.util.DataSource.TYPE_TEXT;

// Define the data schema
itemDataSource.responseSchema = {
recordDelim: “\n“, // Record delimiter
fieldDelim: “,”, // Field delimiter
fields: [“item_id”, “code”, “name”, “description”, “qty”, “unit_cost”] // Field names
};

// Configure pagination features
// The following object literal reiterates default values
var initialRequest = ‘do=items&id=’+ id;
var itemConfigs = {
initialRequest:initialRequest,
pageCurrent: 1, // Show page 1
rowsPerPage: 25, // Show 500 rows
startRecordIndex: 1, // Start at first Record
pageLinksLength: -1, // Show all page numbers in direct links
rowsPerPageDropdown: [10,20,50,100],
singleSelect:true
};
itemDataTable = new YAHOO.widget.DataTable(“itemContainer”, itemColumnSet, itemDataSource, itemConfigs);
itemDataTable.subscribe(“cellClickEvent”, itemDataTable.onEventSelectRow);
}

This being the PHP side which generates the CSV then echoes it out for the JS to pick it up.

$csv_data = ”;
$sql = “SELECT * FROM fran_invoice_items WHERE invoice_id=”.$_GET[‘id’];
$res = mysql_query($sql);

while($row = mysql_fetch_assoc($res)){
$csv_data .= $row[‘item_id’].“,
“.$row[‘code’].“,
“.$row[‘name’].“,
“.$row[‘description’].“,
“.$row[‘qty’].“,
“.$row[‘unit_cost’].“\n“;
}

//You need to trim the last "\n" otherwise the DT won’t render.
$csv_data = trim($csv_data);
echo $csv_data;

Some important points I mentioned on the mailing list are:

  • At the moment there’s no way of having the page numbers for the table at just the top or the bottom. They’re always at both ends. I made a feature request for this but there was a workaround offered by one of the members on the list which you can find here.
  • Whenever I had a column with the “key” as “id” it seemed to assume I meant the YUI generated row ID rather than the fieldname of my data field I sent using CSV. A simple name change sorted it but just a heads up if you try using “id” as a key name in your table – don’t. Give it a name like: “thing_id”.
  • Refreshing the table data after making an edit to the records can be done by re-instantiating the table.

Practice Makes Perfect

January 26th, 2007

Its always good to hone your programming skills outside of your usual day-to-day job with a selection of different challenges.  That’s why I’ve compiled a list of games, quizes and challenge sites for programmers which are useful for any language.

1. Code Kata

Created by Dave Thomas of the Pragmatic Programmers this is a regular blog posting of challenges with a variety of skill levels and challenging various areas.  Well worth a look.

2.  Code Golf

Relatively new but already one of the best open challenge sites on the net.  With a good selection and growing rapidly it promises to be great for beginners and advanced coders alike.

3.  Ruby Quiz

Based on the Perl quizzes of old the Ruby Quiz has been going a while now and relies on quiz submissions by members of the mailing list which are then compiled and sent out with a time limit on solving it and responding with the answer.  All the past challenges are available on the site.

4. The Python Challenge

Not quite as nicely organised and well documented as the Ruby Quiz as this provides challenges for Python programmers in a series of ever-increasing difficulty.

5. Top Coder

One of the oldest and best especially for oldschool challenges and core algorithm programming using lower level languages like C, C++, Java, etc.

If anyone knows of any others then please leave a comment and I’ll add it to the list.

Ajax Scaffold – Improved Search/Filter

June 7th, 2006

I can’t take the credit for this one this time but its a huge improvement on the previous category filter I created using the Ajax Scaffold Generator earlier in the month. This one courtesy of a gentleman at ASG Google Groups who posted a filter with an auto complete search box and after giving it a whirl I’d highly recommend it and I’m already beginning to replace my old category filter in some of my projects.