Thursday, 10 January 2013

Best practice with jQuery

 1. How to select your selector ?

There are various ways of selecting a DOM element in jQuery, but performance depend on how we select our selector.faster to slower-
 $(“#id”) - This is the fastest way of selecting a DOM element.because it uses native document.getElementId() method.
 $(“tagName”) - Use of tag name for selector is also very fast, such as for better performance we can use $(“p”), because it uses native document.getElementsByTagname() method.
 $(“.class”) - This also a fast selector but slow in older versions of IE.It uses native document.getElementByClassName() method. because all above methods have their respective native methods so they are very fast. 
 $(“[attribute=name]”) - Selection by using attribute is slow because it does not have any native method in JavaScript.
 $(“:hidden”) - This is the most powerful but slowest selector in all of above so be careful when we use pseudo-selectors.

2. How to use jQuery Object for Chaining ?

An important fact about jQuery is that its almost all methods returns a jQuery object, its mean we can use multiple methods in a single line.It will make our code slightly shorter and more faster.Example:
$(“obj”).addClass(“try”);
$(“obj”).css(“color”,”red”);
$(“obj”).height(100);

by using chaining we can minimize our code as :
$(“obj”).addClass(“try”).css(“color”,”red”).height(100);

3. How to use Cache ?

If you are using a selector more than one times in your code then its better to use caching in your program.It will improve your program performance.
$(“multiply”).find(“id”).addClass(“plus”);
$(“multiply”).find(“id”).removeClass(“plus”);

by using Cache:
var multi = $(“multiply”).find(“id”);
multi.addClass(“plus”);
multi.removeClass(“plus”)
;

by using cache and chaining both:
var multi = $(“multiply”).find(“id”);
multi.addClass(“plus”).removeClass(“plus”);


4. How to handle events in better way ?

“Event-listeners cost memory”
Whenever we are writing a event-listener than always kept in mind the above statement.
Commonly in our code we uses hundreds of event-listener and jQuery provides us various method for that but how to use efficiently these methods is upto us.Example:
$(“table”).find(“td”).click(function(){
          $(this).toggleClass(“active”); })

Here, we are binding an event to each “td” of table which will take more memory,instead of that we can use “on” method which wrap-up functionality of all jQuery’s previous event-listeners (.bind(),delegate(),.live()). additionally “on” support some other parameters also which helps in delegation.
$(“table”).find(“td”).on(“click”,function(){
          $(this).toggleClass(“active”); })

but in above still we are binding our event with each “td” again wastage of memory, so we can use in such a manner.here we are binding event with our table not  in a particular “td”,so here we reduced our memory uses.
$(“table”).on(“click”,”td”,function(){
       $(this).toggleClass(“active”);})



5.How to separate “CSS” and “jQuery” ?

Instead of changing appearances by jQuery directly, we can use CSS classes for changing  appearances.
$(“table”).css(“color”,”red”);
Instead of that we should make a CSS class and then use jQuery methods to implement that class.Such as:
CSS class:
.red{
 color:red;
}

jQuery:
$(“table”).addClass(“red”);
It will provide us more flexibility, we can easily remove that css whenever required.

6. How to store data in jQuery ?

.attr or .data - Many of us use .attr method for storing data, which is not a good practice.Instead of that we should use .data method for storage. .attr method is for manipulating the attribute.So:
$(‘selector’).attr(‘alt’, ‘this is the data that I am storing’);
           // then later getting that data with
          $(‘selector’).attr(‘alt’);

Here we are storing data with HTML, which are not meant to be.Instead of that we store data in our javaScript code,which is a better idea.
Instead of that we should use:
$(‘selector’).data(‘meaningfullname’, ‘this is the data I am storing’);
// then later getting the data with
$(‘selector’).data(‘meaningfullname’);


Updation continue in this article @ click  you can send your suggestion on java.ansh@gmail.com .

Wednesday, 19 December 2012

Working With Node

Node is a server-side JavaScript interpreter that changes the notion of how a server should work.
Its goal is to enable a programmer to build highly-scalable applications and write code that handles
tens of thousands of simultaneous connections on one, and only one, physical machine.Here we
go with practical implementation of node.

Installing Node.js

1. Download setup for your system from http://nodejs.org/download/, and click on install.
2. You will get a node.js command prompt.

3. *npm will also install with your node.js setup.
or
1. Go to http://nodejs.org/ , and click the Install button.
2. Run the installer that you just downloaded. When the installer completes, a message indicates
that Node was installed at /usr/local/bin/node and npm was installed at /usr/local/bin/npm.

*npm, short for Node Package Manager, is two things: first and foremost, it is an online repository

Now we have a command prompt of node.js like as:
Your environment has been set up for using Node.js 0.8.16 (ia32) and NPM.
C:\Users\{USERNAME}>
After Installing Node.js, we will create a build tool for our Applications, for that we will use a build-in
package Grunt by using npm.
We have a project gruntTool, inside it we install grunt package.

Installing grunt

1. Open node.js command prompt.
2. Reach at project directory or you can use mkdir for making new gruntTool directory.
C:\Users\{USERNAME}\workspace\gruntTool>
3. C:\Users\shai\workspace\gruntTool>npm install grunt
for installing locally in your project.
If you want to install globally in your system use
C:\Users\{USERNAME}\workspace\gruntTool>npm install -g grunt
If we install grunt locally it will create a folder ‘node_module’ in our project.


How to use grunt package

Now in windows if we run our run command grunt.cmd, it will give something like this :
<FATAL>Unable to find ‘grunt.js’ config file. Do you need any --help? </FATAL>
For using grunt full potential we needed a ‘grunt.js’ file in our project, for that we use grunt init
command. It gives us five currently available templates:
● jQuery: A jQuery plugin
● node: A node module
● commanjs : A commanJS module
● gruntplugin: A Grunt plugin
● gruntfile:A Gruntfile(grunt.js)

If your project does not belong to anyone you can use final one gruntfile, Because we are creating
a simple tool so we will go with final one.
With command :

grunt init:gruntfile

you will see something like that:
Running “init:gruntfile”(init) task
This task....................................................
…................................................................
…................................................................
“gruntfile”template notes:
….................................................................
….................................................................
Please answer the following:
[?] Is DOM involved in any way? (Y/n)
[?]Will files be concatenated or minified? (Y/n)
[?]Will you have a package.json file? (Y/n)

After answering these questions it will show done, without any errors. We get a package.json and
grunt.js file in our project directory.
In our package.json , we get the information about our version, name, type, dependencies, and
in grunt.js we get grunt.initConfig and grunt.registerTask. In grunt.initConfig we get some default
tasks such as min, concat, lint, jshint, qunit and watch.
In register Task we register out tasks as:

grunt.registerTask('default', 'lint qunit concat min');

So when we use command grunt.cmd (for windows) all four tasks are run by default.
Now we will create a source folder src, in which we have three separate folders for javascript,
html and css. These folders can have other folders inside them.
Our project directory will look like this:

gruntTool
          |__ node_modules
          |__ src
                  |__ javascript
                  |__ html
                  |__ css
          |__ tasks
          |__ target
          |__ grunt.js
          |__ package.json
          |__ config.json


tasks folder: is for creating your own tasks.
config.json file is for creating token.

Create different Environment
Classify the tasks which we want to do in different environment. For example “DEV” and “PROD”
     dev :

                Concat JavaScript .

                Remove temporary files and folders.
               Copy css and html files from src to target.
               Zip your target folder

   Prod :

               concat javascript .

               Minify javascript .
               Minify css.
               Remove temporary files and folders .
               Copy html from src to target .
               Zip your target folder

We can see there are some common tasks which should run in both cases so how we can configure our tasks? We are going to configure tasks according to their environments.

Concat javascript

We have something like
concat: {
    dist: {
      src: ['<banner:meta.banner>', '<file_strip_banner:src/FILE_NAME.js>'],
      dest: 'target/FILE_NAME.js'
    }
  },

This is the task which is in-build in grunt, now we can divide this task for different environments as follows

concat : {
    prod: {
      src: ['<banner:meta.banner>', '<file_strip_banner:src/FILE_NAME.js>'],
      dest: 'target/FILE_NAME.js'
    },
     dev : {
      src: ['<banner:meta.banner>', '<file_strip_banner:src/FILE_NAME.js>'],
      dest: ‘target/FILE_NAME.js'
    }
  },

Here, we can see our task is divided in different environment. And we can register tasks as:

grunt.registerTask('dev', 'lint qunit concat:dev min');
grunt.registerTask('prod', 'lint qunit concat:prod min');

For running our dev tasks we use command
grunt.cmd dev

For running our prod tasks we use command
grunt.cmd prod  .

Register your config.json file

For tokenizing or making task for scalable we use a config.json file and register file in our grunt.js file as:
config : '<json:config.json>'

Minify css

We have various ways of minifying css, grunt build-in function min in only for the minification of javascript(till now).we will try two approaches for minification.
By using YUI compressor

1. Download the jar file in your project directory from http://www.java2s.com/Code/Jar/y/Downloadyuicompressor247jar.htm  .
2. Write a task in your tasks folder ‘mincss’ as :
   var exec = require('child_process').exec;
    grunt.registerTask('mincss', function() {
      grunt.log.write("Minifying css using yuicompressor \n");
      var cmd = 'java -jar -Xss2048k ' + __dirname
              + '/jar/yuicompressor-2.4.7.jar --type css ' // Explicitly download YUI compressor.
              + grunt.template.process('<%= config.data.src %>*.css') + ' -o '                 + grunt.template.process('<%= config.data.dest %>main.min.css')
      exec(cmd, function(err, stdout, stderr) {
          if (err)
              throw err;
      });
  });

we can see we are using exec in our task so we need to require child_process package, which we can install as npm install child_process .
3. Now we need to register our task in grunt.js file as:
 grunt.task.loadTasks('tasks');
4. Now we can register our mincss task as
grunt.registerTask('prod', 'lint qunit concat:prod mincss');

Finally we are able to minify our css.One more thing we are using config.json file for our address which would look like as:
  {
"data": {
    "src"       : "src/**/*"
    "dest"      : "target/"
}
}

but this is very complex, let’s try another one.

By using grunt-css package
1. Install npm install grunt-css  .
2. Register your task in grunt.js file as
 grunt.loadNpmTasks('grunt-css');
3. Now structure of cssmin task put in your grunt.js file as :
 cssmin : {
          files : {
              src : '<%= config.data.src %>*.css',
              dest : '<%= config.data.dest %>/main.min.css'
                  }
              },
4. Register your task for environment as :
 grunt.registerTask('prod', 'lint qunit concat:prod cssmin');
These are two ways of css compression. I personally feel that second one is better than first because of its less complexity.  

Copy files
If we need to copy some files from src to target than, we need to install another package as :
1. npm install grunt-contrib
2. Load your package in your grunt.js file as:
  grunt.loadNpmTasks('grunt-contrib');
3. Task writing :
  copy: {
         prod : {
     files : {
      "<%= config.data.dest %>" : "<%= config.data.src %>.html",
              }
          }
          },

4. Register your task for suitable environment as:
   grunt.registerTask('prod', 'lint qunit concat:prod mincss copy’);
  
Zip folders

Now for zipping a folder we need to install a new package as :
1. npm install grunt-contrib-compress  .
2. Load your package for grunt.js file as :
  grunt.loadNpmTasks('grunt-contrib-compress');
3. Task writing :
   compress : {
          zip : {
                files : {
          '<%= config.data.dest %>.zip' : '<%= config.data.dest %>/**'
                  }
                }
          },
4. Register your task for suitable environment as:
     grunt.registerTask('prod', 'lint qunit concat:prod mincss copy compress’);


Clear temp files
During the execution of various tasks, sometimes we create various temp files or folders, at last we need to remove that folders and files from our project. For that we use another package as :
1. npm install grunt-clean
2. Loading task as :
  grunt.loadNpmTasks('grunt-clean');
3. *task writing:
  clean : {
          folder : "target/",
          file : "temp/"
         },
             
  * Syntax of task should be correct, src and target addresses should be correct, because it is not a stable version and it sometimes deletes your whole project. So everything should be written in correct way.
4. Register your task for suitable environment as:
     grunt.registerTask('prod', 'lint qunit concat:prod mincss copy clean compress’);

Note:
Apart from that if you are using grunt-cli latest version of grunt than keep in mind following points:
During installation follow the following instruction otherwise it will give you fatal error.

Solution for v1.4
1. npm install -g grunt-cli
2. npm init
  fill all details and it will create a package.json file.
3. npm install grunt (for grunt dependencies.)

Saturday, 10 November 2012

Web Servers

Hi, Today we have a quick look on how our web servers really works.We started with a very simple example which we use daily. Nowdays we are using a client-server model for our web applications.Our client means browser request to server for a particular query and according to that our server responds. When we put a URL(Uniform Resource Locator ) in our browser than how it actually works?
We have our URL such as:

http://www.google.com/index.html

Our web- browser divide that URL into three parts.
1. http: It is a protocol which provide connection between client and server. There are many more such as https for secure connection, ftp for file transfer,ftps for secure file transfer , mms for microsoft streaming and many more.
2.www.google.com: It is a address of the server by which our computer contacts when you try to access some information or a web page.
3.index.html: It is a resources which was requested by our computer.It is a particular web page.

So,when your type a URL and press enter than request is sent to the server in this manner.When server gets your request than usually server replies with HTML code.Our browser takes that HTML and interpreted with graphics and shows us the result.There are various server packages who serves for our web pages such as Apache.Our browser sends a standard request to server and our server serves according to the request in standard manner. Here we discuss about HTML respond which is static in nature but it could be a dynamic such as php,jsp etc.

Auto-Wiring in Spring

Auto-wiring is a way of resolving the beans that need to be injected by inspecting the elements in ApplicationContext. Auto-wiring reduces the configuration for the properties and constructor.If configuration is changed for the property bean than it automatically updated.There are 4 kind of auto-wiring :
1.No (Default).
2.byName.
3.byType.
4.Constructor.

In 'default' auto-wiring means there is no wiring and we are still using the ' ref ' keyword for connecting beans. In 'byName' auto-wiring Spring uses the property 'name' and searches a bean with same name as property and  wired it .In 'byType' auto-wiring Spring uses the property 'type' and searches beans with same type as our property and wired it.If there are more than one bean with same type than it will give us a error as :

" Error creating bean with name 'person' defined in class path resource [Dependency.xml]: Unsatisfied dependency expressed through bean property 'name': : No unique bean of type [studyMaterial.Name] is defined: expected single matching bean but found 2: [name1, name2];"

So when you are using 'byType' than there should be only one bean of that type.In the same way if we are using constructor and in our constructor we are using property than it can also be auto-wired by using '   'autowire ="constructor"'.Here is a simple picture for representing auto-wiring.

No auto-wiring:
Auto-wiring :

Here we can see by using 'autowire' we can reduce the configuration of our xml file. Person is a class having property 'name' which is a type of  'Name' , so Spring searches for 'Name' type and bean 'name1' is a Name type because we are implementing 'Name' interface in our 'studyMaterial.DisplayThisName' class.So it connect name1 with person implicitly.One more thing I like to share in this topic which is annotation based wiring, so lets have a look.


Annotation Based Bean-wiring: 

 

Till now for wiring we are using "autowire" attribute. Ok how It would be if didn't need that anymore in our xml file and Spring automatically wire your beans.sounds good......na, ya we can do it by using annotation in our application. Some things needed for configure the annotation.
1.We have to add some files such as :
  •  xmlns:context="http://www.springframework.org/schema/context" .
  •  http://www.springframework.org/schema/context .
  • http://www.springframework.org/schema/context/spring-context-2.5.xsd .
  •  <context:annotation-config/>
Here is our configured file for our person and name example,

                                                                                                 
Now we can see that we need no attribute for wiring it automatically searches for you beans and wired it.One more thing, in our Person class, just above the property declaration we have to put a "@Autowired" keyword just like as:


Now it is complete and you can see that still our program running successfully without using autowire keyword.So enjoy with annotations.


Your mail are always welcomed at java.ansh@gmail.com.