May 12 2009

Google and Yahoo JavaScript CDN

One way to speed up loading of a website is to use Content Distribution Networks (CDN) for resources that don’t update often, such as JavaScript, images, and CSS. A good CDNs for a large site can run into the thousands of dollars, fortunately for those that rely on JavaScript frameworks such as jQuery, Prototype, and YUI you can use the use Google’s and Yahoo’s broadband.

Google hosts a large number of JavaScript libraries, including jQuery, jQuery UI, Prototype, Dojo, and even YUI! Using the JavaScript libraries hosted on Google should make your page load faster. Google give you an absolute URL address for each version of the JavaScript library you are trying to use, this makes it easy to load the required scripts.

http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

Yahoo also provides free hosting of the Yahoo! User Interface from their servers.

One theory why using Google hosting for jQuery and similar hosted JavaScript frameworks is that if many of the sites you visit use them, your browser will already have a fresh cached version ready for you. My question is, why don’t browsers come pre-installed with the commonly used versions of JavaScript libraries? Odiously, if this feature would be enabled from the top tier browsers there would also need to implement a discovery mechanism to download into a browser repository new versions of those JavaScript libraries. A code discovery, management, and repository system that I have seen work well is that provided by Maven. In Maven, you can indicate a number of online and local code repositories from which to download required dependencies.


May 11 2009

The Anatomy of a JavaScript Bookmarklet

I think of bookmarklets as a way to greasemonkey patch a webpage with custom JavaScript not approved by the author of the website you are visiting. Bookmarklets are a bit of JavaScript that you save as a bookmark and when visiting a page, if you click on that bookmark, the JavaScript will run on the context of the current page that is being viewed. This allows you to modify the current page in ways that the original author did not think off or allow. In essence, bookmarklets are a way to extend, modify, and enhance sites you are visiting.

Common examples of bookmarklets are the Amazon Universal Wishlist, Tumblr share bookmarklet, and DZone submission bookmarklet. In the case of the Amazon bookmarklet, when you click the bookmarked JavaScript a new frame dialog pops up that allows you to select an image from the current page, add a price, and title and then add that product description to your Amazon wishlist. The Tumblr and Dzone bookmarklets help in submitting the current page to their respective services as a social bookmark.

Bookmarks are not new, they have been around since JavaScript was first introduced, but it is a technique that opens a lot of opportunities for a power users. Bookmarklets allows your users to submit information to your service about and from whichever website they are visiting.

Here is the hello world example of a bookmarklet.

javascript:alert('hello, world!');

Type the above code snippet in the location bar of your browser and click enter! You should have seen the alert dialog pop up with the correct greeting. That is your first bookmarklet.

To allow users to save the JavaScript bookmark as a bookmarklet into their favorites or bookmark toolbar you will need to create a link. Here is an example of a link with a bookmarklet.

<a href="javascript:alert('hello, world!');">Say Hello</a>

Now that we have the mechanics of a bookmarklet down, lets go over some practical scenarios. In the examples listed above, the bookmarklet simply loads an additional JavaScript source file that acts as the main application which in turn may load additional resources such as images and CSS files. Once all the resources have been loaded, from the main JavaScript source file, you can invoke the necessary methods.

Here is an example of the JavaScript bookmarklet which will load the secondary JavaScript main application source file. This bookmarklet simply acts as a loader. Notice that for the actual bookmarlet, the JavaScript needs to be escaped and obfuscated into a single line.

(
  function(){
    var w=window,
        u='<url TO MAIN SCRIPT>',
        l=w.location,
        d=w.document,
        s=d.createElement('script'),
        e=encodeURIComponent,
        x='undefined';

    function g(){
      if(d.readyState && d.readyState!='complete'){
        setTimeout(g,200);
      }else{
        if(typeof MainApp==x) {
          s.setAttribute('src',u+'.js');
          d.body.appendChild(s);
        }
        
        function f(){
          if(typeof MainApp==x){
            setTimeout(f,200)
          }else {
            MainApp.show();
          }
        }

        f();
      }
    }
    g();
  }()
)

Again, you need to obfuscate the above JavaScript into a bookmarklet by removing all non-essential white spaces and line breaks. The bookmarklet should all fit in a single line in the href of a HTML link. That said, lets explain the above bookmarklet a bit. The first thing that will happen is that the a new HTML script tag will be created for the main JavaScript source file. The script will set timeouts until the additional script file has been downloaded, interpreted, and the MainApp object is defined. Once the MapApp object has been defined you can invoke the custom code that will run in the browser in the context of the current web page. The MainApp object is defined in the JavaScript file which was loaded by the bookmarklet.

For completeness sake, here is a simplified trivial example of the main JavaScript source file.

var MainApp = function(){
  var greetings = function(message) {
    alert(message);
  }
  
  return {
    show: function() {
      greetings('Hello, World');
    }
  }
}();

Remember that the main JavaScript source file can load additional resources, ask for user input, and post data back to your server. It runs in the context of the current page you are visiting and has access to all elements in the DOM. In my opinion, bookmarlets are the easiest way to enhance a page without using a browser plugin or extension.


May 11 2009

Dynamically Create HTML Elements with JavaScript

Twenty-five percent of AJAX is the J part, the JavaScript. When working with dynamic data coming from the back end you must create the necessary DIV containers and HTML elements and append the new new elements into the document body. In FireFox you can create a new element using the createElement method on the document object. It is good to note that creating an element this way just creates a object, and does not actual insert the element into page until you append it a parent element node.

var link = document.createElement('a');
link.setAttribute('href', 'http://juixe.com');
link.innerHTML = "Hello, Juixe!";
document.body.appendChild(link);

This is all simplified with jQuery, especially since jQuery normalized the browser quarks and differences. Here is the equivalent code but using jQuery, note that you need to load the appropriate jQuery JavaScript version for this work in your browser.

var link = $('a');
link.attr('href', 'http://juixe.com');
link.html('Hello, TechKnow!');
$('body').append(link);

All that can be streamlined and broken down to two lines.

var link = $("<a href='http://juixe.com'>Hello, jQuery!</a>");
$('body').append(link);

Using jQuery you can actually create more complex HTML elements than a simple link.

var link = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
$('body').append(link);

May 9 2009

Repetative Recursion

One of my pet tech peeves is repetition and redundancy. I wish documentation had the same level of reuse as code. But in reality I find that we tend to repeat ourselves even in code just for duplication’s sake and we don’ realize it. Were I see a lot of superfluous repetition that is easy to overlook is in naming of variable, fields, columns, and classes. Here are a few examples of what I mean.

You have a folder called ‘Experience’ and under that all files are named like the following ‘exp_search_test.xml’ filename. The filename repeats that this document is an experience, whatever that really means. If you really want to indicate a file is of a given data type use the extension, so you rename the file as ‘search_test.exp’ or ‘search_test.exp_xml’ to indicate the file type.

Another example dealing with code is that variable names repeat their purpose. For example, you have an Employee class and the class has a subsequent employeeFirstName. If the variable is inside the Employee class, it is not required to prefix the class name to each field name. Use the context of the class to define meaning, don’t ad verbose comments to repeat what is clearly obvious like ‘This is the employee first name.’

I see this same problem in database column names. Another example that comes to mind of a real database schema used in production is of a fund table with column names such as fund_long_name, fund_type, etc. Again, I prefer concise and succinct column names.

Let me repeat myself again, if you try to add context to field name where it is already obvious you actually populate the namespace. Here is a more concrete example of that, again from code used in production. There was an ExcelExport class that contained the following two methods, exportExcel() and urlExportExcel(URL). Which method name should we refactor to simplify the API? … You might be thinking to rename urlExportExcel(URL) to simply exportExcel(URL) and in this way provide a concise API by overriding the same name but with different parameter list. Remember, the method signature of most languages includes the parameter type/list. But I would not stop there, I would actually rename the exportExcel() and exportExcel(URL) method names to simply export() and export(URL)! Why? Well, because you don’t just export data to Excel, you usually export data in different formats and flavors such as XML, RSS, CSV, etc. I hope that you can now see, that simply naming this method as export and using polymorphism, interfaces, subclasses, and factory pattern you simplify not just your method names but code.

An example of recursive repetition is where a word in the dictionary refers a different word, but if you look up the second word it refers to the first. As rule of thumb to avoid dubious verbose recursive repetition, variable names are not comments and comments should not repeat variable declarations.


May 7 2009

Laws of Source Code and Software Development

I’ve worked in a variety of projects, in a myriad of languages, and have learned the following universal truths about software development the hard way.

  • Commented out code are not comments – Use version control, don’t track code changes by commenting them out. Commented out code is schizophrenic code.
  • Let your reputation and code precede you – If you work on open source projects, blog, and work your network, you will get more job offers even when you aren’t looking for a job than people that are looking for a job and just email out resumes.
  • Don’t make excuses for code, let it speak for itself – You are paid to find solutions using code, not find excuses for your code. ‘It worked on my machine’ is not a solution. You will not ship out your computer to the client with the application.
  • Don’t take code personal – Don’t take code reviews personally, it is not about you but a business feature and the overall performance of the application.
  • Your code is your career legacy – For years after you leave, those that will maintain your code will either curse you or thank you.
  • Coding does not equal programming – Writing code is not the same thing as software development, one requires thought while the other does not. Just like playing with your iPod does not make you a musician.
  • Code is about learning – Moore’s Law states that technology doubles every 18 months, you should keep up. If you are not learning you are doing it wrong. Every project is an opportunity to learn.
  • Code is communication – People will read the code you write. Use best practices and common design patterns and idioms. Strive for simplicity over impressing the monkey on your back. Your code should communicate clearly and concisely it’s intent. Code talks, bugs walks!
  • It is not the tools that make a developer – Know your tools and use them to their full power but don’t use them as a crutch! Switching between IDEs should not stop you on your tracks because you can’t find the correct code generation wizard. Michelangelo was a great artist with nothing more than a chisel and a slab of marble.
  • Don’t trust your code – Trust in your coding abilities does not replace repeatable testing. Don’t trust your code, assumptions, or users.
  • Code is not written in Latin – Code is not dead once the application ships. Code is always refactored, modified, re-used, and evolving. Your greatest strength is not writing mountains of new lines of code but maintaining, refactoring, and herding existing code into performing business requirements as per an agreed specification.
  • Respect the API – Your API is a contract others will depend on. Keep the API clean and explicit! The least amount of methods you expose is less testing and maintenance and documentation that you need to maintain.
  • Code outlives its intention – As much as you would like, writing your application from scratch in the latest programming language or framework will not benefit the number of end users that for one reason or another are stuck with the current version of the software. Code can outlive it’s original intention, design for extensibility and adaptability.
  • Code means different things to different people – In the end, to end users code simply means the ability to do what they expect.

May 5 2009

Top JavaScript and Web Performance Presentations on Google Tech Talks

Google has a YouTube channel with over 1000++ videos of presentations on a large number of programming and software development topics. Here are the top videos recently released in the Google Tech Talks channel regarding JavaScript and web performance that every web developer should see.

  • JavaScript: The Good Parts / Douglas Crockford – In JavaScript there is a beautiful, highly expressive language that is buried under a steaming pile of good intentions and blunders. The best nature of JavaScript was so effectively hidden that for many years the prevailing opinion of JavaScript was that it was an unsightly, incompetent abomination. This session will expose the goodness in JavaScript, an outstanding dynamic programming language.
  • Drop-in JavaScript Performance / John Resig – Browsers are continually upgrading – providing new features from the latest specifications. We’ll look at modern JavaScript and DOM techniques that you can easily drop in to your applications for instant speed-ups.
  • Best Practices in Javascript Library Design / John Resig – This talk explores all the techniques used to build a robust, reusable, cross-platform JavaScript Library such as jQuery.
  • High Performance Web Sites and YSlow / Steve Souders – Yahoo!’s Exceptional Performance Team has identified 14 best practices for making web pages faster. These best practices have proven to reduce response times of Yahoo! properties by 25-50%.
  • Life’s Too Short – Write Fast Code / Steve Souders – Techniques to help yoru web site perform better are discussed such as coupling asynchronous scripts, use iframes sparingly, and flush the document early.
  • Debugging and Testing the Web with Firebug / Rob Campbell – In this talk we explore web development and debugging strategies with Firebug. An overview of new and improved features and how to use them is presented. We wrap-up with a peek at FireUnit, a new Firebug extension by John Resig and Jan Odvarko, and it’s role in unittesting Firebug itself.
  • Faster HTML and CSS: Layout Engine Internals for Web Developers / David Baron – How fast Web pages load and how fast they change dynamically depends on both the Web page and the browser it’s running in. Browser makers put significant effort into making their browsers faster, but there are also things that Web page authors can do to make their pages more responsive.
  • jQuery / Dmitri Gaskin – jQuery is a JavaScript library that stands out among its competitors because it is faster, focuses on writing less code, and is very extensible.