Jun 4 2012

JavaScript Debugging With The console Object

In the early days of JavaScript there were few options for debugging large web applications. You could have used the multiple alert notifications or possibly even calling document.write to write messages into the document. Firebug changed web developers lives, and I think how we view JavaScript, by making it incredibly easy to debug HTML, CSS, and JavaScript. Since Firebug, most current versions of web browsers include powerful debugging tools. In addition to the debugging tools browsers have made available a JavaScript console object to help write debug statements. With console, there is no need to pop up alerts to inspect the state of an object. To write a log message intended for the console, just write the following JavaScript statement in the right place.

console.log("This is a log message");
console.log("Message one", "Message two", "Message three");

To open the console, you can find it in Safari by looking for the the Web Inspector, in Chrome it’s called Developer Tools, and in Firefox you’ll find it under the Tools menu as Web Console.

The console object has a lot of useful debugging messages for errors with different severity, such as log, debug, info, warn, and error.

console.info("I'm here.");
console.warn("Do I smell smoke?");
console.error("The roof, the roof, the roof is on fire.");

In addition to logging String messages, you can log whole JavaScript objects. It may be useful to inspect a complete object and it’s state. To write out the state of an object to the console use the dir method as in the following example.

console.dir({fname:"Bill", lname:"Gates"});
console.dir(document.getElementById('SomeElementId'));

In Chrome and Safari, you can also use dirxml to display the a HTML element object in the console as HTML. In my version of Firefox, this method did not work.

console.dirxml(document.getElementById('SomeElementId'));

You can also group related log messages, no matter their severity. To group console messages surround them with a group and groupEnd. You can even nest groups inside of groups.

console.group("Server update");
console.log("calling server...");
// ... any number of console log messages.
console.groupEnd();

You can also test the performance of your JavaScript code with time and timeEnd. Both of these methods accept a String label and it needs it needs to be the same value for both methods.

console.time("Process Data");
// ... some time consuming code
console.timeEnd("Process Data");

When the timeEnd method is executed it will generate a message in the log console with the amount of time it took to run the code between the time and timeEnd method.

Chrome Developer Tools Web Console

Chrome Developer Tools Web Console


Nov 14 2011

jQuery Mobile + PhoneGap = Awesome Mobile Development Platform

I’m currently prototyping an iPad application and I’ve just found working with jQuery Mobile and PhoneGap to be a breeze for mobile application development. I’ve used iOS SDK before and I’ve experimented on test applications with Android and I’ve always found issues with both the iOS and Android development frameworks. I’ve also looked into cross platform mobile development toolkits such as Appcelerator Titanium and Sencha Touch but I found these were not of me at the time. Any of the aforementioned platforms and frameworks can be used to create a great looking and functional mobile application but I found that they each ask the developer to make a trade off.

With jQuery Mobile, you develop your mobile application with HTML5 and JavaScript/jQuery. With jQuery Mobile, all of your UI is written in pure HTML5 tags with the correct CSS classes and attributes. jQuery Mobile is built on top of jQuery so many web developers can immediately start being productive with jQuery Mobile.

Everybody has an idea for the next great iPhone application. The top reasons I’ve heard from people, including from developers, as an excuse for not getting started is that they don’t have a Apple computer, they don’t want to learn another programming language, they don’t have time, etc. jQuery Mobile invalidates all of these excuses. You can use Firefox or Chrome to test your jQuery Mobile application, you develop using plain HTML5 and JavaScript, and most it’s easy to pick up.

Because a jQuery Mobile application is just a HTML5-based web application, if your an run it on your iPhone or other mobile device using the native web browser. On the iPhone, when you run a jQuery Mobile application the browser will take up a small portion on the screen for the navigation buttons, bookmarks, and other controls of the browser. One way to claim all of the screen real-estate is to create a native application, that is where PhoneGap comes in. PhoneGap is a native shell around a web application, such as those developed in jQuery Mobile. With PhoneGap, you can turn your jQuery Mobile application into a full fledged native application.


Dec 24 2010

iPhone Frameworks

As mobile devices become more and more entrenched and as more mobile devices become available there is a growing number of people that want to quickly develop an idea into an app. Developers of all sorts are picking up Objective-C to develop the next top selling mobile-based and touch enabled app. If you don’t want to learn Objective-C, there are several mobile frameworks to choice.

    Rhomobile – A cross-platform mobile app development.
    Titanium – A cross-platform native application stack.
    MonoTouch – Write iPhone and iPod Touch applications in C# and .NET.
    iWebkit – A simple framework to create your own iPhone and iPod Touch webapps.
    TapLynx – Rapidly develop iPhone, iPad, and iPod Touch Apps without learning Cocoa.
    PhoneGap – PhoneGap is an open source development framework for building cross-platform mobile apps.
    jQTouch – A jQuery plugin for mobile web development on the iPhone, iPhone Touch, and other forward-thinking devices.
    Cocos2D for iPhone – A framework for building 2D games and graphical applications.

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);