My Talks at phpXperts Seminar 2010

My recent talks on JavaScript at phpXperts Seminar 2010 : “Beauty of Web“, the biggest tech seminar at Dhaka.

.

My topic titled “JavaScript Wash” covered the followings:

  • Common JS issues
  • JS in Mobile Application Development
  • Interactive UI samples
  • Open Source JS Libraries
  • The High-Performance JS Mantra
  • JavaScript Development Tools

If you liked this talk then rate this talk

Cheers! 🙂

Advertisements

jQuery Plugin Authoring – Step by Step

.

If you interested in JavaScript and jQuery plugin development then this one is for you(who have at-least jQuery plugin usage)

.

1. Add a new function property to the jQuery.fn object:

jQuery.fn.myPlugin = function() {

// plugin goes here

};

jQuery.fn is shortcut form of jQuery.prototype

2. Wrap up it with a self executing closure.

(function( $ ){
$.fn.myPlugin = function() {

// plugin goes here

};
})( jQuery );

$ in place of jQuery
it’s a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign
so it can’t be overwritten by another library in the scope of its execution.

3. In the immediate scope of the plugin function, the this keyword refers to the jQuery object the plugin was invoked on.

(function( $ ){
$.fn.myPlugin = function() {

this.hide(); //the this keyword is the jQuery object of the DOM element on which you are pluging-in

};
})( jQuery );

4. jQuery selector query can match zero, one or more elements. This scenarios need to be considered when designing plugin

$.fn.myPlugin = function() {

this.each(function(){
//each() provides implicit iteration
});

};

5. Method chaining are a required behavior. Most cases We need to return a jQuery object from all plugin methods.

$.fn.myPlugin = function() {

return this.each(function(){
var $this = $(this);//have the jQuery object of the invoked element cahced for further use

});

};
With this we can chain our plugin method with built-in methods like

$('div').myPlugin().css('color', 'red');

6. Make your plugin configurable and put some default options too

$.fn.myPlugin = function(options) {

var defaults = {
 speed: 30, //some test data options here
 duration: 2000,
 frequency: 10000,
 //.....
 spread: 3
 }; //default options

//inherit from provided configuration (if any)
var options = $.extend(defaults, options);

return this.each(function(){

    var $this = $(this);
    //more stuffs goes here
});
};

7. Add some more functions

$.fn.myPlugin = function(options) {

var defaults = {
 speed: 30,
 duration: 2000,
 frequency: 10000,
 //.......
 spread: 3
 }; //default options

//inherit from provided configuration
var options = $.extend(defaults, options);

return this.each(function(){

    var $this = $(this);

    //some more functions added here
    var function1 = function(){};
    var function2 = function(){};

   function1(); //call functions to perform

});

};
8. Namespacing

Properly Namspacing your plugin assures that your plugin will have a very low chance of being overwritten by other plugins or code living on the same page.

9. Documentation
In-file documentation should be prepended to each function or method definition in proper format.

10. Example plugin:

A demo “Shake an Element” plugin created for more understanding of jQuery plugin structure which can be download from here 🙂

11. Usage

All plugin files must be named jQuery.myPlugin.js where myPlugin is the name of the plug-in.

Append your jQuery.myPlugin.js at the head section of your HTML Document.

<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jQuery.myPlugin.js"></script>
<script>
$(document).ready(function($) {
$('selctorQuery').myPlugin({speed:10,duration:3000,..spread:5});
});

</script>
</head>
12. Optional but useful 🙂

Compress and Minify your plugin codes

Packer

This JavaScript compressor/obfuscator by Dean Edwards is used to compress the jQuery source code. It’s available as a web-based tool or as a free download. The resulting code is very efficient in file size, at a cost of a small increase in execution time:

http://dean.edwards.name/packer/

http://dean.edwards.name/download/#packer

JSMin

Created by Douglas Crockford, JSMin is a filter that removes comments and unnecessary white space from JavaScript files. It typically reduces file size by half, resulting in faster downloads:

http://www.crockford.com/javascript/jsmin.html

JavaScript Object Literal Namespacing

JavaScript Object Literal is a comma separated list of name-value pairs enclosed within a curly braces, means of encapsulating lots of data under a namespace, where the name is a valid variable name and the name can be used as variable. Values can be of any data type, including array literal and object literal.

Purposes of JavaScript Object Literal notion:

  • It provides encapsulation
  • Avoiding global namespace pollution
  • Relatively straightforward to implement

A namespace is a context for identifiers, simply a namespace is an abstract container for items such as names, objects etc. Also within a namespace, the components can not share the same name.

Encapsulation, In his influential book on object-oriented design, Grady Booch defined encapsulation as “the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation.”

An example given as:

/*
* BlogPost : creating BlogPost object using object literal notation
* basic structure: {name:value, name:value};
* or can be as { name:value, { name:function(){...},...}, name:value ... }
*/
var BlogPost = {

 title: 'Welcome to My Blog',  // Blog title
 numberOfView: 0,    // Number of Blog view
 blogContent: '',    // Blog post content
 URL: 'https://mahtonu.wordpress.com', // Blog post URL
 flag: false,        // Use some flag
 lastView: null,     // Timestamp of the last Blog view

 //set blog content here
 setContent: function(content) {
 this.blogContent = content;
 },
 //get blog content
 getContent: function() {
 return this.blogContent;
 },
 //count the number of blog post view
 incrementView: function() {
 this.numberOfView++;
 },
 //set timestamp of the last Blog view
 setTimeStamp: function(time) {
 this.lastView = time;
 },
 //get timestamp of the last Blog view
 getTimeStamp: function() {
 return this.lastView;
 },
 //get blog url
 getBlogUrl: function() {
 return this.URL;
 }
};

In the avobe example the  “BlogPost” object created using object literal notion with some properties. Thus the property values can be manipulated using methods sharing the namespace. Further adding property or methods are simple enough.

More usage:

//set some post here
BlogPost.setContent('I am a body of a blog post!');
BlogPost.setTimeStamp('14th April 2010 09.00PM');
//publish your blog post
document.write('Title: '+BlogPost.title);
document.write('Post: '+BlogPost.getContent());
document.write('Link: '+BlogPost.getBlogUrl());
document.write('Posted at: '+BlogPost.getTimeStamp());
document.write('Total Viewed: '+BlogPost.numberOfView);
//got a hit increment your view no
BlogPost.incrementView();

So we are accessing and working around the properties of an object forming a namespace.

References /Further Readings:

Wiki page for Information hiding [Encapsulation Part]

Tim McCormack on Javascript object literal namespacing

Jonathan Snook on Objectifying JavaScript

Good JavaScript Study Resources

🙂

Rules, Naming , Conventions

Google JavaScript Style Guide

JavaScript: The World’s Most Misunderstood Programming Language by Douglas Crockford (2001)

http://javascript.crockford.com/javascript.html

“Private Members in JavaScript” by Douglas Crockford (2001)

http://www.crockford.com/javascript/private.html

Code Conventions for the JavaScript Programming Language

http://javascript.crockford.com/code.html

ECMA-262-3 in detail

http://dmitrysoshnikov.com/

OOP: The general theory.

http://dmitrysoshnikov.com/ecmascript/chapter-7-1-oop-general-theory/

Object Oriented Programming in JavaScript

http://mckoss.com/jscript/object.htm

.

Using Google’s CDN to load JavaScript libraries

For rich Ajax web applications page loading time suffers from loading JavaScript libraries such as JQuery, MooTools, Prototype etc..  Most of them are larger than 50KB in size and if you are in need to combine libraries then you are adding 100KB+ to your page loads.

Also your web server will experience delivery of your own hosted JavaScript libraries across distinct geographical requests. You can easily offload your server for those files.

Assuming all possible ways to improve JavaScript libraries loading time, Google’s CDN aka Google Libraries API can be a good solution.

Why Google CDN? Why not my own server?

  • The Google Libraries API is a content distribution network and loading architecture for the most popular, open-source JavaScript libraries.
  • Google’s huge CDN (content delivery network) can deliver the file much. Since Google has large data centers all over the world, these files will be served from data centers geographically closer to your users. This helps to reduce network latency and add to reliability, scalability and so on.
  • The more sites that include Google’s google.load() API the greater the chance that a user has already has the file cached, thus enabling your site to load faster as the script will not need to be downloaded.
  • You save bandwidth as you no longer have to serve the file(s).
  • The versioning system that Google has created makes it effortless to include specific versions of these libraries.

All you need to do is make a Google’s Libraries API call google.load() like:


<script src="http://www.google.com/jsapi" type="text/javascript"></script>

google.load("chrome-frame", "1.0.2");
google.load("dojo", "1.5");
google.load("ext-core", "3.1.0");
google.load("jquery", "1.4.2");
google.load("jqueryui", "1.8.4");
google.load("mootools", "1.2.4");
google.load("prototype", "1.6.1.0");
google.load("scriptaculous", "1.8.3");
google.load("swfobject", "2.2");
google.load("yui", "2.8.1");
google.load("webfont", "1.0.6");

.

Minor Drawbacks

  • You’re dependent on the CDN infrastructure. If they are down, your website will be hardly usable, too.  But that case u have to write extra codes to check the desired library loaded or not.
  • You cannot influence bandwidth and carriers of the delivery provider’s network.

Reference: http://code.google.com/apis/libraries/devguide.html#AjaxLibraries

.

🙂

Precaching images with JavaScript

Most of the time images on your page take extra seconds to download from web server. Again if you want to load some images on some user action, you most likely want the fast image load i.e. instant with the user clicks..
Or in case you want to create an image gallery viewer by clicking ‘Next’ / ‘Previous’, you usually don’t want waiting your user for some extra seconds for each image loading.

JavaScript helps you to load images into the browser’s memory cache without displaying them.This technique is the hilarious precaching images. And this technique preload the images into the browser cache when the page initially loads.

In order to precache an image we need to construct an image object in memory. Image object created in memory is dissimilar from the document image object aka <IMG>tag.

Here we go

var myImage = new Image(width, height)

Parameters to the constructor are the pixel width and height of the image we want to precache.
So the image object exists in memory. Now you can assign a filename or URL to the src property of that image object:

myImage.src = “someImage.jpeg”

Such above statement assigning image src loads the image into the browser image cache.

Now you can use this cached image wherever you like instantly.
You may assign this precached image src property to the actual document image tag src property.

document.images[0].src = myImage.src

Here is the detail example:

<html>
<head>
<title>Image viewer</title>
<script type="text/javascript">

//precache four images
image1 = new Image(480, 320)
image1.src = "1.jpg"
image2 = new Image(480, 320)
image2.src = "2.jpg"
image3 = new Image(480, 320)
image3.src = "3.jpg"
image4 = new Image(480, 320)
image4.src = "4.jpg"

//loads an image from cache
function loadFromCache(img){
	document.imagePlaceHolder.src = eval(img + '.src')
}
</script>
</head>

<body>

<div align="center">
<img name="imagePlaceHolder" src="1.jpg">

<br>

<a href="#" onClick="loadFromCache('image1')">Image1</a>
<a href="#" onClick="loadFromCache('image2')">Image2</a>
<a href="#" onClick="loadFromCache('image3')">Image3</a>
<a href="#" onClick="loadFromCache('image4')">Image4</a>

</div>
</body>
</html>

In the above example four images are precahced into browser memory and used in the page <IMG> tag src property oncilck on the four links instantly updates the document <IMG> tag src. Try the example and feel the difference in image loading. 🙂

Download this example code with some sample images

Tadddaaaa!

Self executing functions in JavaScript

JavaScript has bunch of cool features; one of them can be self executing functions. 🙂

Also this self invocation feature could be surrounded by the best practices for JavaScript.

Let’s have an example of an anonymous self invoking function:

 (function(){
 var test =  2;
 alert(test);
 })();
 

Here, test variable has its own local scope, means it doesn’t interface with or pollute global scope and it dies out(remains as long as there’s somewhere in the page or in an event that references the variable you declared in your closure: Thanks Dan Beam for this correction 🙂 ) when the function terminates.

One simple example:

 var testVar = "Hi there";

(function testFunction(str)
{
alert(str);
})( testVar );

One more scoping example(by Dan Beam):

var class = (function () {
var private = function () { alert("Hey, I'm still here!"); };
return ({ test: function () { private(); }});
})();

// more JavaScript

class.test();

Self-invocation (also known as auto-invocation) is when a function executes immediately upon its definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development.

I am a great fan 🙂 of it because:

  • It keeps code to a minimum
  • It enforces separation of behavior from presentation
  • It provides a closure which prevents naming conflicts

Enormously – (Why you should say its good?)

  • It’s about defining and executing a function all at once.
  • You could have that self-executing function return a value and pass the function as a param to another function.
  • It’s also good for block scoping.
  • Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. 😉

jQuery pursue such struct.

 (function($) {
 // $() is available here
 })(jQuery);
 

It’s precisely the reason that jQuery doesn’t pollute the global namespace nearly as much as other libraries.

Cheers!

😀

Updating your page dynamically with Ajax.Updater – Prototype API

Ajax.Updater

Well most of web devs desire Ajax to update parts of the document by receiving HTML fragments. If I assume right that you are one of them then this one is for you. Also we are going to approach below in Prototype.js way 🙂

By the way, Are you a jQuery lover? If yes, then you should know jQuery(1.4.x) doesn’t provide such facility directly  😉

Normally in prototype.js – ajax, we execute Ajax.Request(Click here in case ur not familiar with it) to make our asynchronous requests.

In order to update part of your HTML document with HTML fragments, with Ajax.Request with an onComplete callback this is fairly easy, but with Ajax.Updater it’s even easier! 😀

Ajax.Updater: Performs an AJAX request and updates a container’s contents based on the response text.

Lets have some real example below:

Suppose you have such a portion in your HTML document

<h2>List of My Girlfriends </h2>
<!-- By the way, how many GF do you have? -->
<div id="girlfriends">(fetching girlfriends list ...)</div>

And you are suppose to fill that “girlfriends” DIV with…


new Ajax.Updater('girlfriends', 'gfManager.php', { method: 'get' });

That’s all. 🙂 No hassle… It will update your “girlfriends” DIV with girlfriends name list.

And your server end script responded well and looks like below:

<h2>List of My Girlfriends </h2>
<div id="girlfriends">
<ul>
<li> Emma Watson </li>
<li> Nora Ali </li>
<li> Jessica Parker </li>
</ul>
</div>

The arguments are the same of Ajax.Request, except there is the receiver element in the first place. Prototype will automagically update the container with the response using the Element.update() method.

And if you are smart enough you can implement this one in your own way.

Here i built my own username availability checker at some user signup page:

<form>
<label for="username">username:</label>
<input type="text" name="username" id="username" onkeyup="checkUserName();" />
<div id="availability"></div>
</form>

with this checkUserName method

function checkUserName() {
 if($F('username').length == 5) {
 var url = 'chkusername.php';
 var params = 'username=' + $F('username');
 var ajax = new Ajax.Updater(
 {success: 'availability'},
 url,
 {method: 'get', parameters: params, onFailure: reportError});
 }
}
function reportError(request) {
 $F('availability') = "Error";
}

The server end script does query the database and responds whether the username taken or not.
Which looks like below:

If the username is available

If the username is already taken

Cheers! 😀

Ajax with Prototype JavaScript framework

Before starting with Prototype AJAX, if you wish to have some basic Ajax talks you can visit my previous post

Prototype.js

Prototype is a JavaScript Framework which provides an Ajax framework and other utilities. It offers a familiar class-style OO framework, extensive Ajax support, higher-order programming constructs, and easy DOM manipulation.

I love Prototype Framework due its robustness all the way 😀

Prototype’s Ajax

Besides simple requests, this module also deals in a smart way with JavaScript code returned from a server and provides helper classes for polling.

Ajax functionality is contained in the global Ajax object. Actual requests are made by creating instances of the Ajax.Request object.

Ajax.Request (All you need for using AJAX in Prototype API)

new Ajax.Request('/some_url', { method:'get' });
//Initiates and processes an AJAX request.

The first parameter is the URL of the request; the second is the options hash.
The
method option refers to the HTTP method to be used; default method is POST.

As Ajax requests are by default asynchronous so you must have Callbacks in order to handle server response data and those callback methods should be passed in the options hash.

Ajax response callbacks

new Ajax.Request('/some_url',
 {
 method:'get',
 onSuccess: function(transport){
 var response = transport.responseText || "no response text";
 alert("Success! \n\n" + response);
 },
 onFailure: function(){ alert('Something went wrong...') }
 });

Here, two callbacks are passed in the hash that alert of either success or failure; onSuccess and onFailure are called accordingly based on the status of the response.
Other available callbacks are:

  • onUninitialized,
  • onLoading,
  • onLoaded,
  • onInteractive,
  • onComplete and
  • onException.

They all match a certain state of the xmlHttpRequest transport, except for onException which fires when there was an exception while dispatching other callbacks.

Parameters with the request

You can pass the parameters for the request as the parameters property in options:

new Ajax.Request('/some_url', {
  method: 'get',
  parameters: {name: 'Tonu', age: 27}
  });

The main idea to use parameter option is sending the contents of FORM with the request and yes of-course Prototype has it’s helper to do serialize.

new Ajax.Request('/some_url', {
  parameters: $('id_of_form_element').serialize(true)
  });

Global responders

Again if you wish to register some callbacks which will fire on certain state and will work with every Ajax.Request
then you have
Ajax.Responders, a repository of global listeners notified about every step of Prototype-based AJAX requests.

If you wish extend your reading then Click Here

More on Ajax with Prototype Here

Cheers! 😀

inArray in JavaScript

First of I would like to say that JavaScript doesn’t provide inArray or in_array method to check if a value exists in an array like php do PHP: in_array 😦

Well we have some good options instead 😀

But before using some custom inArray method, you better know that if you are a jQuery freak then this post is not for you because jQuery have a nice utility jQuery.inArray() – jQuery API

Yeah! we are talking about raw and plain JavaScript implementation of in_array in JavaScript.

For this we are going to add a inArray prototype method into Array class of JavaScript using simple linear search inside that method like below:

Array.prototype.inArray = function (value)
{
 // Returns true if the passed value is found in the
 // array. Returns false if it is not.
 var i;
 for (i=0; i < this.length; i++)
 {
 if (this[i] == value)
 {
 return true;
 }
 }
 return false;
};

Awesome! right 😀

Now we will use it in terms of JavaScript feature as we have already added inArray method as Array class method

var testArr= ["Shrek","Feona","Donkey"];
//use of inArray
if(testArr.inArray("Donkey"))
   document.write('Are we there yet!!!!');
else
   document.write('Thank God!!!');

Here with our inArray prototype method implementation we are able to access inArray using DOT(.) with the given array object where most of the in_array methods takes main array as haystack and a value as needle such as in_array(search_value,array) .

This function should work fairly well on relatively small lists of items. For a larger array, a binary search function may be more appropriate.

In this way you may implement some more handy javascript prototype method.

Cheers! 🙂