Thursday, July 19, 2012

Messing with CSS: Art of construction

All the developers enjoy working with CSS and what more it is more fun when you are working with cross browser issues (sarcasm :)). A simple definition of cascade is descending waterfall, which has the same meaning with style sheets too and that is the beauty of CSS. Rules that are defined later get applied to the elements as compared which are defined earlier. Author style sheets are applied prior to user style sheet which are applied prior to user agent style sheets with the only exception that user !important will have higher precedence over author !important.

Layout

How do you want your page to look like? or How do I make my page to look same as the Adobe image sent to me by graphics/UX team? Darn! it makes my life crazy. CSS is pretty handy for page layout, it can be used to create custom layouts and then layouts can be reused as templates for other pages. Most of the web page needs are around either column layout || row layout which leads to grid layout. CSS layouts are basis for Responsive Web Design.

Theme-ing

Modern day world users expect to change theme of application, well if they can for desktop why not for desktop look RIA application. There are many ways to do it. CSS is divided into two categories one is visual like color, font, images etc. and structural for e.g. padding, margin, width etc. In most of the theme requirements its the visual which is changing and structural almost remains the same. Given that, we can divide the CSS into two files for each module under visual and structural folders. The files under these folder defines the default theme for the application. 

CSS File Structure


Now product requirement is to have a Ferrari theme with rounded corners, red colors, ferrari images etc. We create a new folder named Ferrari under our CSS/visual directory and create a file called as theme.css. In this file we will override the class for appropriate theme changes. Now lets say we get three more theme requirements for Corvette, Mustang and Porche. We follow the same process we followed for Ferrari and create three more theme.css files. What do we do now? Lets include all the CSS on to the DOM and while including link has attribute "title" give the name of the theme as value:







Now we need JavaScript DOM magic to work with UI, when user request for change in theme, javascript code has to iterate through the list of links on the document and check if they have title. Set the link disabled to true to all except but one which has the same title as requested by user. By setting the link disabled to true we are making CSS referenced by link disabled for the document. Using this approach user gets real time and awesome experience with changing the theme.


MyApp.changeTheme = function (title) {
    var cssLink;
    var cssLinks = document.getElementsByTagName("link");
    var i;
    for (i = 0; i < cssLinks.length; i++) {
        cssLink = cssLinks[i];
        if (cssLink.getAttribute("rel").indexOf("style") !== -1 && cssLink.getAttribute("title")) {
            cssLink.disabled = true;
            if (cssLink.getAttribute("title") === title) {
                cssLink.disabled = false;
            }
        }
    }
};


Challenges

Not to mention there are many. I would like to mention two which are not so obvious on IE. Here they are:

1. IE has a limit to the number of CSS which can be included in a give document. It is limited to 31 CSS files, all the files included after 31st file will not be referenced in document.

2. Another interesting problem, combined and compressed CSS file gets huge and then on IE only some part of the CSS from that file is recognized and rest is ignored. why? because IE has another limitation which says per file IE allows only 4095 selectors. Now I feel like killing myself but hang on suicide is a crime. To address this issue we will have to page the compressed and combined CSS file.

Not to mention CSS3 has given new dimension to web development. Flexible grids, layouts, images, etc all leading to Responsive Web Design where one application will scale on various screen resolutions.


















Monday, June 18, 2012

JavaScript: Fun with Closure! “A state of being closed”

This is another fun and interesting aspect in JavaScript programming. Closures are powerful because they enable inner functions to retain access to an outer function's variables even after the outer function has returned. Let’s try to understand it in a fun way.

JavaScript Closure: Analogy

A King has lots of GOLD which he has kept in a secret treasure. There is a map which leads to treasure but its only King who knows about it. King decides that only after his death prince should get map which should lead prince to the Treasure of GOLD. King in which case is an outer function which gives life to inner function but makes sure that after its execution has ended inner function which is prince has access to treasure. Lets take a look at following code and represent it in technology way:

            var King = (function(){
                     var treasureMap = 'Map to treasure';
                     this.myPrince = function(){
                            alert(treasureMap);
                     }
                     return {
                            prince:this.myPrince
                    }         
             })();

In  above code King is class and has private variable treasureMap which is not exposed because the function has been executed as soon as it is defined (module pattern). Lets see if King has treasureMap:

                        alert(King.treasureMap); // Oops it comes as undefined 


which means king may have it but is not revealing it which fulfills our use case.

King left prince as successor, it will be interesting to see if prince knows about it or not because King is dead and cannot access treasureMap.

                        King.prince(); // Alerts 'Map to treasure' Hurray!

How this happened? Closure is the answer. King.prince is the inner function in King which knows about treasureMap and has access to it even though King has left the world. This is closure which enabled prince to retain King's treasureMap property even when King has returned from execution call.


Closure: Memory Leaks

Like any other good thing, closure comes with challenges too. As long as closures are active, this memory cannot be garbage collected. Therefore, closures can lead to memory leaks if not used well. Lets examine a use case where it can lead to memory leak. Most of the memory leak in JavaScript is due to circular reference between javascript object and DOM element. For e.g.

               <html>
               <body>
               <script type="text/javascript">
                              window. preProcess(){
                               var obj = document.getElementById("elId");
                               obj. createLeak(){
                                              //Some processing
                                              alert("Adding leak");
                               };
                               obj.something=new Array(1000);
                              
               };
               </script>
               <button id=" elId ">Test Me</button>
               </body>
               </html>

In the above example on load of window function preProcess will  be executed which will create a new JavaScript object obj with reference to DOM element elId and the DOM element has reference to JavaScript object thereby creating a circular reference. It is important to break this circular reference in order to address memory leak from the code. Simplest way to achieve this is to set JavScript obj to null when that object is no more required.

               <html>
               <body>
               <script type="text/javascript">
                              window. preProcess(){
                               var obj = document.getElementById("elId");
                               obj.> createLeak (){
                                              //Some processing
                                              alert("no leak");
                               };
                               obj.something=new Array(1000);
                               obj = null; // set the object to null to break circular reference
                              
               };
               </script>
               <button id=" elId">Test Me</button>
               </body>
               </html>

Server side programming in JavaScript with nodejs, expressjs, stylus, jade etc. makes efficient use of closure. In conclusion, a closure in JavaScript is like keeping a copy of the all local variables, just as they were when a function exited.

Tuesday, June 12, 2012

ExtJs || jQuery || YUI

When I meet people they ask me which is good; ExtJS or jQuery or YUI or may be Dojo and this is what I feel and say. Over past few years I have worked with some of these libraries with more extensively on ExtJS and YUI (with yui-ext, does that rings a bell ☺?).


I like it. Solves the purpose!
It is very well crafted Object Oriented JavaScript library for Rich Internet Applications. It is beautiful to write classes, extend them, override methods, create objects, and encapsulate objects in JavaScript with ExtJS. It is like working with any other OOP language like, where one can use extend and understand what that means. Out-of-box  collection of component or widgets are efficient and extensible. Wonderful layouts makes the job easy for developer like card layout, border layout etc. Store makes the job easy to store data in data-structure which has rich API for query etc. Components like grids, tabbed panels, form, tree etc. are customizable and extendable and makes ExtJS even more attractive. Good community contributing to plugin development. Good documentation with implementation examples. 

It is not open source. I feel it is good for applications where there is not a whole lot of business logic happening on the client and there is less frequent DOM manipulation. It is thick on client with the amount of code it has. Until ExtJS 4 the architecture doesn’t really follow the MVC pattern, the view is either encapsulating the model or tightly coupled to model.

It is a good RIA JavaScript library and has lot into it.

Smart & Intelligent!
jQuery is one of most widely used and popular JavaScript framework in web application development. It is very thin on client. It has extensive API for DOM manipulation. It has huge community support which is contributing to jQuery and making it more rich. UI components are usually extensible and can be customized as per use. If I have web application which requires AJAX and UI tweaks then jQuery is one good solution. Documentation is good and it has ease of learning. It is very to use and integrate into existing project.

UI components are limited but there are plugin from the community. Plugins can be unstable depending on their quality. Complex UI components are not part of jQuery. Plugins might require more work to make it work with the application.



Cool!
YUI has evolved over the period of time. I have worked with YUI 1.6 with yui-ext which was extension of YUI with lots of other features. Out of box components set is rich and can be used with existing application. It was one of the first to let access to their library over the web. Documentation is extensive and it has good set of examples. It is backed up by yahoo and they have used it most or all of Yahoo’s web applications which make a good point for YUI.

YUI lacked good syntax for JavaScript. It took time to evolve through the generations of JavaScript libraries. YUI led to foundation of other libraries but could not develop the similar momentum for itself.

Now to answer the big question “Which one to use for my application”? Answer is very simple:  It depends on the application and what that application intent to do, if the application is to give RIA feeling, less data intensive on client, faster development and funding is enough to buy a rich library go for ExtJS. If price is crunch and library has to be open source and should be extensive on client DOM manipulation then jQuery is very good solution. KnockoutjsBackbone.js and many other libraries have either plugins or extensions with jQuery. YUI is also good for such applications but one lacks community and it is good for converting parts of web application into RIA easily.

No matter what I like all three of them and I feel if one implement them well they all solve the purpose.



Monday, June 11, 2012

Why blogging?



I don't know how to blog or shall I be honest and say I don't how to write good blog which interests you. I will do something which will help me bring out what is "inside me". I am excited when I am writing this first blog. I don't want my blogs to be boring and too monotonous, I will try if we can have fun together.

Here is what I feel which is making me blog:
  • I am focused on software engineering, Agile, Scrum, fitness and family.
  • There are three ingredients in good life: learning, earning and yearning.
  • I feel I can spread what I have learnt so far in my life which might benefit you.
  • I feel it is my way of communicating and letting you know what I am and what I can be.
Life is small so live it to the fullest. For those who know me understand what I meant by that, if not come over and I will make it happen.

I am all excited and hopeful that I continue this and make it interesting for both of us.