Category: Javascript

building a nice image gallery like pinterest/friendsheet using facebook graph api and LightBulb

Pinterest has gained lots of attention lately and became popular in the photographer’s and designers community from the very beginning. And once something is popular, people copy (and sometime with improvement) their beautiful user interface ideas into their own project. Last week i’ve seen quite a traction when friendsheet was released. They allow you to browse photos from your Facebook news feed in a nice and organized way.

When we saw friendsheet last week – me and Rifat were discussing that it could be a nice demonstration if we develop a image gallery with our revolutionary project LightBulb (seriously, someday something’s gonna change the world – so keep dreaming big).

LightBulb is an extensive wrapper of Facebook Open Graph objects sitting on top of their JS SDK. You can interact unbelievably easily with graph objects using a wrapper like LightBulb without worrying too much about underlying technology and the core API itself. LightBulb is stable, easy to use, there are already lots of examples within it. Hasn’t been officially released yet but we are planning to do so in a week or two. Stay in touch.

So back to the point, our main intention was to show LightBulb’s capability of pulling FB graph objects and show them in a nice way like FriendSheet. The final output looks similar to that of Pinterest/Friendsheet and guess what, for only 10-15 lines of JS πŸ™‚ with another couple of lines added in the stylesheet block.

Demo: http://demo.projectlightbulb.net – For download link of source code, keep reading πŸ™‚ . If you dont see the gallery (or sometime see a little overlapping sometime) please refresh and it will work like a charm. It’s fully compatible and responsive with your mobile device.

The hovering effect is done using jQuery Adipoli Hover plugin. The stacked display is done by using jQuery Masonry plugin.

LightBulb is under active development from the developers at Leevio ( Me, Shoriful Islam Ronju and Rinku Arnob) , Rifat Nabi and M.A Hossain Tonu.

Download the Facebook Gallery using LightBulb from here (Thanks Box.net)

Shameless Promotion
If you want to outsource your Facebook application development to us, feel free to contact us here. Why? Because we know Facebook app development and their open graph objects inside out πŸ™‚

Getting comfy with PhpStorm – one of the best IDEs so far!

Beside the frequently asked question “Which Framework is best?” this one is the top in category – “Which one is the best IDE”. People asks this question in morning, afternoon and evening. Every-time, everywhere. I am a big time fan of Netbeans and I left it a few days after it’s release of 6.7. It was so good, heavenly, yummy but I had to leave this old pal because of it’s extreme hunger to the available resources. There was only one thing that time which could compete with the resource hungry netbeans – that is FireFox. But hey, FF is not your IDE after all. Anyway, back to my point – I left Netbeans and started using PhpStorm. I have a company license and I am glad that I made this move. I am not going to preach PhpStorm in rest of this article, but what I will do is sharing my experience with PhpStorm πŸ™‚

1. PhpStorm is fast: Not like a Bugatti Veyron beside your old 4 wheelers, but it’s fast. I was told that 64 bit version is even faster but that was not true in my macbook pro running snow leopard. rather I found that 64 bit version is slightly sluggish and more resource extensive. Whatever, when you make a jump from Netbeans to PhpStorm, you will really feel the speed of everything and if you keep an eye over your system memory, you will surely say “wow!”.

2. The best Javascript and X/HTML Intellisense: I am a javascript developer for almost 8 years by now. I have tried eclipse, some standalone components which could also run as eclipse plugin and Aptana. Aptana was good – I was using aptana mostly because of it’s auto-completion capability of javascript. But I really HATE eclipse. Why? – I will write a separate blog post on that. Now Netbeans has some capability of intellisense for Javascript but when it comes to jQuery (remember, I left NB at it’s 6.7th release) it was frustrating. PhpStorm really is beautiful for this. Just amazing! The format, the auto suggestion, the code completion everything works just perfect. This is one of the main reason why I am sticking with PhpStorm

3. Version Controlling: Ya ya I know, NB got that too. I am not a Netbeans hater, rather I love it. I love how amazingly it changed my world of coding by charging me nothing – zip, zilch nada! So it is merely a selling point for making a move from NB to PhpStorm – but the thing is, support for different VCS in PhpStorm is as good as like the other parts of it. It has fantastic support for Git and Svn, beautiful tools for merging and fixing the conflicts, refactoring and what not. I was feeling at home and to be honest, migrating from NB to PhpStorm didnt feel like I came to the land of aliens just for this. Without integrated support for VCS it would be impossible for me to stay with PhpStorm.

4. Less hungry: Though Steve Jobs said to stay hungry and foolish but please note that he said it only for humans, not to IDEs :P, lol! Ok, so PhpStorm is less hungry to CPU and Memory than NB. I just wish Firefox will be a performer like this one day πŸ™‚ (different story again, sorry I am distracted with too many things at once)

5. Less Costly and a Friendly company: Phpstorm is a developer friendly company. I am using the licensed copy of Zend Studio since 2005 (I got that for free because of being a ZCE and because of winnign some competitions over time) but heck! Zend Studio is costly. That’s fine, Zend Studio is the PHP company and knows inside out of making a PHP IDE. But trust me, PhpStorm is not an alien thing at all – you will not feel “vim” with this excellent tool. PhpStorm can help you code PHP, HTML, CSS and JS with maximum comfort. Yet, it costs much less than other similar IDEs with similar feature set. And what did I mean by “Developer Friendly”? PhpStorm team listens to you. Most of the time you mail them for a discount, they give you some sort of discount without expecting anything from you (I love you, PhpStorm team for this). Even Elite in the class Zend Studio gives some discount some time. But try the same with Elite of the Elites like Coda. They wont take their time to say “Go, fuck yourself!” – I hate Coda, seriously! So rude!

Anyway – that’s a long story. I am very happy with PhpStorm and has recently upgraded my IDE from 2.x to 3.x with their one year full update support (even with major versions :D, Zend you should really think about that with Zend Studio) and living happily ever after. Love you PhpStorm, I really do!.

Get your 30 days trial version of PhpStorm from http://www.jetbrains.com/phpstorm and feel a whole different level of satisfaction πŸ™‚ And surely, dont forget to check NetBeans too, that’s a beautiful piece of tool.

jQuery Mouse Direction Plugin

jQuery provides support for standard JS mouse events as well as some custom ones. In jQuery it’s easy to capture whether mouse point has entered in the boundary of an object or left from (mouseenter, mouseleave) or something else happened (like click, dblclick etc). But you are in trouble if you need to capture the direction of your mouse. And it would be fantastic if there was a plugin which can fire custom mouse-direction event on any elements which you can then listen to and bind a listener routine.

I wrote this small plugin (jQuery MouseDirection Plugin) this afternoon to trigger eight custom event for any visible element in the DOM structure. Here is the source code. This plugin registers eight custom directional event like up,down,left,right,top-left,top-right,bottom-left, bottom-right and one more generic event called “mousedirection” where you can capture the direction of the mouse using event object’s “direction” parameters (like event.direction)

[sourcecode language=”javascript”]
/**
* jQuery Mouse Direction Plugin
* @version: 1.1
* @author Hasin Hayder [[email protected] | http://hasin.me]
*/
(function ($) {
var options = {};
var oldx = 0;
var oldy = 0;
var direction="";
$.mousedirection = function (opts) {
var defaults = {
};
options = $.extend(defaults, opts);
$(document).bind("mousemove", function (e) {
var activeElement = e.target || e.srcElement;
if (e.pageX > oldx && e.pageY > oldy) {
direction="bottom-right";
}
else if (e.pageX > oldx && e.pageY < oldy) {
direction="top-right";
}
else if (e.pageX < oldx && e.pageY < oldy) {
direction="top-left";
}
else if (e.pageX < oldx && e.pageY > oldy) {
direction="bottom-left";
}
else if (e.pageX > oldx && e.pageY == oldy) {
direction="right";
}
else if (e.pageX == oldx && e.pageY > oldy) {
direction="down";
}
else if (e.pageX == oldx && e.pageY < oldy) {
direction="up";
}
else if (e.pageX < oldx && e.pageY == oldy) {
direction="left";
}
$(activeElement).trigger(direction);
$(activeElement).trigger({type:"mousedirection",direction:direction});
oldx=e.pageX;
oldy=e.pageY;
});
}
})(jQuery)
[/sourcecode]

An here is how you can use it

[sourcecode language=”html”]
<head>
<title>jQuery Mouse Direction Plugin Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.mousedirection.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
.container {
height: 150px;
margin: 20px;
padding: 20px;
width: 300px;
border: 1px solid #888;
}
</style>
<body>
<div class="container">
Move your mouse over this box
</div>
<script type=’text/javascript’>
$(function () {
$.mousedirection();
$(".container").bind("mousedirection", function (e) {
$(this).html("Mouse Direction: <b>"+e.direction+"</b>");
});
});
</script>
</body>
[/sourcecode]

To save from the overwork of running a check whether the mouse has entered on the supplied DOM elements (via selectors) I have located the active element under the mouse pointer and triggered the event only on that object – this was a huge performance boost πŸ™‚

Download the complete plugin with the example.html from the link below

Download jQuery Mouse Direction Plugin

πŸ™‚ Enjoy!

Working with Facebook events using Graph API, JS-SDK and PHP-SDK – part 1

Graph API from Facebook is a very interesting project based on open graph protocol. Facebook is gradually setting Graph API as the standard and deprecating the use of their old REST based APIs. To start working with Graph API doesnt need an extensive knowledge on how Facebook API works but its always good to have a sound knowledge on that. Graph API uses oAuth based authentication mechanism and using the auth token, they can identify who is making the API calls. I have been working on Facebook events using Graph API for last couple of days and I will be sharing my experience in this series of two or three posts where I am going to cover the following topics

1. Authenticating a user
2. How to create a Facebook Event with picture
3. How to post on Events Wall
4. How to manage users
5. How PHP SDK can be a life saver in some cases πŸ™‚

Authenticating a user
Its very important that you know how to authenticate an user against Facebook and ask for appropriate permissions to be granted. To work with public events in Facebook, you need to ask for “create_event” permission from your visitors. Otherwise, in case of private events, you need to be granted permission for “user_events” and “friend_events”. For now, lets consider that we will be creating public events and we will ask for only “create_event” permission.

Lets create a new application in Facebook which will point to our working url. The following screenshot will show you which informations are necessary to create such an app. Once you are done, save the API_KEY/APP_ID and SECRET_KEY safe in somewhere for later use.

Facebook App Properties
Facebook App Properties

Now you are done with creating a Facebook app, its time to code πŸ™‚ The following codeblock will prompt any visitor to log in with Facebook and grant the application some permissions. We are using our JS-SDK. We are also saving the auth token. You will soon find out why that would be necessary.

[sourcecode language=”javascript”]
<!html>
<head>
<title>My Facebook Event App</title>
<script src=’http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js’></script>
</head>
<body>
Welcome to our New Facebook App <span id=’fbinfo’><fb:name uid=’loggedinuser’ useyou=’false’></fb:name></span>
<div id=’fb-root’></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type=’text/javascript’>

var fbuserid, fbtoken;
var appid = "224818724242243";
var loggedin = false;
$(document).ready(function() {
//loginFB();
});

FB.init({appId: appid, status: true, cookie: true, xfbml: true});
FB.Event.subscribe(‘auth.sessionChange’, function(response) {
if (response.session) {
var session = FB.getSession();
fbtoken = session.access_token;
fbuserid = session.uid;
}
});

FB.getLoginStatus(function(response) {
if (response.session) {
var session = FB.getSession();
fbtoken = session.access_token;
fbuserid = session.uid;
}
else{
loginFB();
}
});

function loginFB() {
FB.login(function(response) {
if (response.session) {
var session = FB.getSession();
fbtoken = session.access_token;
fbuserid = session.uid;
}
}, {perms:’create_event’});
}

function logoutFB() {
FB.logout(function(response) {
// user is now logged out
});
}

</script>
</body>
</html>
[/sourcecode]

Now when you visit your application url, for example http://ev.tekzon.net in our case, you will be prompted an authentication windows like this

Authentication Dialog
Authentication Dialog

So now users are successfully authenticated to our new Facebook application, lets move to the next part

Creating a Facebook event using JS-SDK
To create a Facebook event, we need to pass the following parameters to “/me/events” graph url.

  • name: Name of the event
  • start_time: Start time of the event in UNIX timestamp format, or in “mm/dd/yyyy H:i” format πŸ™‚
  • end_time: End time of the event in UNIX timestamp format, or in “mm/dd/yyyy H:i” format πŸ™‚
  • location: Location of the event, as a string
  • description: Description of the event
  • picture: Profile picture for the event, we can not use that with JS SDK.
  • privacy: either “OPEN” or “PRIVATE”, we will use “OPEN” in this example

So, here is a Javascript function which can create this event. In the following codeblock you will find a wrapper javasript function “createEvent()” to create this event and an example function to use that createEvent() function

[sourcecode language=”javascript”]
function createEvent(name, startTime, endTime, location, description) {
var eventData = {
"access_token": fbtoken,
"start_time" : startTime,
"end_time":endTime,
"location" : location,
"name" : name,
"description":description,
"privacy":"OPEN"
}
FB.api("/me/events",’post’,eventData,function(response){
if(response.id){
alert("We have successfully created a Facebook event with ID: "+response.id);
}
})
}

function createMyEvent(){
var name = "My Amazing Event";
var startTime = "10/29/2011 12:00 PM";
var endTime = "10/29/2011 06:00 PM";
var location = "Dhaka";
var description = "It will be freaking awesome";
createEvent(name, startTime,endTime, location, description);
}
[/sourcecode]

Now once you invoke this “createMyEvent()” function, it will show you the event id of your newly created event, if successful. Lets see how that would look like.

Successfully created a new event
Successfully created a new event

Ok, we can see that the event id of our newly created event is “253320941378247” – we can check it out in Facebook by going to http://facebook.com/events/253320941378247 – Meanwhile we can also check this same event using open graph protocol by going to http://graph.facebook.com/253320941378247

Ok, so now we know how to create a Facebook Event using JS-SDK and Graph API. But there is a major problem in creating a Faceboko event using JS-SDK and that is, you cannot attach any Profile Picture with this event. And you have to use a server side SDK (we will be using PHP-SDK in the following example) to do that. Lets see how can we create a Facebook event with a profile picture.

Creating a Facebook event with Profile Picture
We need to post the event parameters (use Ajax) to our server side script. Lets assume that the image file we are planning to use as the Profile Picture for our Facebook event resides in “/path/to/my/image.jpg”.

Here is a very important information for you and that is such an image’s minimum width MUST BE 100px – There is no documentation on that, and apparently I had to waste almost 4 hours to find what is the problem with my code. I just wish Facebook API documentation were better mentioning such things which may lead developers to waste huge time.

Ok, in the following codeblock, we will be using a new javascript function “createMyEventWithPHP()” which will post the event data to our server side php script event.php – Before that, download the PHP-SDK of Facebook from http://github.com/facebook/php-sdk, unzip and place in the same path where you are keeping this “events.php”

[sourcecode language=”javascript”]
function createEventWithPHP(name, startTime, endTime, location, description) {
var eventData = {
"access_token": fbtoken,
"start_time" : startTime,
"end_time":endTime,
"location" : location,
"name" : name,
"description":description,
"privacy":"OPEN"
}
$.post("/events.php",eventData,function(response){
if(response){
alert("We have successfully created a Facebook event with ID: "+response);
}
})
}
[/sourcecode]

And here is the source code of our events.php

[sourcecode language=”php”]
<?php
include_once("facebook-php-sdk/src/facebook.php");

define("FACEBOOOK_API_KEY","224818724242243");
define("FACEBOOK_SECRET_KEY","d57acde94xxxxc3d50a2x2yya9004476");

$name = $_POST[‘name’];
$token = $_POST[‘access_token’];
$startTime = $_POST[‘start_time’];
$endTime = $_POST[‘end_time’];
$location = $_POST[‘location’];
$description = $_POST[‘description’];

$fileName = "./me2.jpg"; //profile picture of the event

$fb = new Facebook(array(
‘appId’ => FACEBOOOK_API_KEY,
‘secret’ => FACEBOOK_SECRET_KEY,
‘cookie’ => false,
‘fileUpload’ => true // this is important !
));

$fb->setAccessToken($token);

$data = array("name"=>$name,
"access_token"=>$token,
"start_time"=>$startTime,
"end_time"=>$endTime,
"location"=>$location,
"description"=>$description,
basename($fileName) => ‘@’.$fileName
);
try{
$result = $fb->api("/me/events","post",$data);
$facebookEventId = $result[‘id’];
echo $facebookEventId;
}catch( Exception $e){
echo "0";
}
?>
[/sourcecode]

When we will invoke createEventWithPHP() javascript function, it will post all the event data to our PHP script. Then PHP script will create that event with Facebook PHP-SDK and print the newly created event id. Say for example, this newly created event id is 129312137169841, so we can go to http://facebook.com/events/129312137169841 and see how it looks with the profile picture

Facebook event with profile picture
Facebook event with profile picture

So thats for today, folks. I will be coming back with more of Facebook Events and Graph API in my next part. Stay Tuned.

Shameless Promotion πŸ™‚ : By the way, if you are looking for a beautiful Admin Panel Theme for your PHP based projects/web-applications, you may want to check out Chameleon Circuit, which is developed by our Themio Team πŸ™‚

Chameleon Circuit - Full Featured Admin Theme from Themio
Chameleon Circuit - Full Featured Admin Theme from Themio

jShutterBox plugin for some cool animation + content display, together

jShutterBox is a jQuery plugin I have developed two or three months ago. But I didnt release it because It was complex and users had to supply content for every animated images. Though it was ok with me that time, but last week I thought that I could make it even simpler to use. For example, just a &ltdiv> containing an image and an anchor can be converted into an animated content box πŸ™‚

to use jShutterBox is simple. Just download the package from Box.net, include jshutterbox.js in your page, and run the following code πŸ™‚

[sourcecode lang=”html”]
<div class="animated">
<img src="http://scripts.ofhas.in/jshutterbox/images/image2.jpg"/>
<a href="http://leevio.com" title="Leevio">Welcome to Leevio</a>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".animated").jShutterBox({slide:"random"});
});
</script>
[/sourcecode]

You can configure other options, like “height”, “width”, “duration”, “borderWidth”, “borderColor”, “slide”. You can pass “random” as a value of “slide” to see the random animation. You can also specify any value of the “up,”down”,”left”,”right”,”up-left”,”up-right”,”down-left”,”down-right”for “slide” to see any specific animation too πŸ™‚

You can view the demo at http://scripts.ofhas.in/jshutterbox/demo.html

I hope you will like it πŸ™‚ – by the way, this plugin depends on jQuery Easing plugin.

Download jShutterBox from DropBox

Shameless Note πŸ™‚ : By the way, if you are looking for a beautiful Admin Panel Theme for your PHP based projects/web-applications, you may want to check out Chameleon Circuit, which is developed by our Themio Team πŸ™‚

Add flexible configuration panel to DOM Elements with jQConfigurator jQuery Plugin

jQConfigurator jQuery Plugin

If you hover mouse over your Facebook profile, you will notice a nice configuration panel appears at the top right corner of your profile picture, saying “Change Picture”

Configuration panel at the top right corner of your profile picture

Now if you want to add nice and flexible configuration panels like this to your DOM container elements like

you can do it easily with jQConfigurator jQuery plugin. This plugin allows you to add text or images based panel items and manage their “click” events easily. Here is a screenshot of what it will look like, once added

Demo: jQConfigurator Object with Image Icons

Or may be one like this

Demo: Using text items in jQConfigurator

For an extensive documentation and working demo + download, check the jQConfigurator plugin from http://scripts.ofhas.in/jqconfigurator . jQConfigurator is released under New BSD license.

Box.net widget in MiproApps – why did it require special care…

In MiproApps, our Visual Facebook Fanpage Desiger from Leevio, everything is built on top of a scalable plugin based architecture. Every plugin manages it’s data using a central plugin manager. Most of these data are isolated from each other, stored and served by the plugin manager without any special coding required from plugin developers. That makes everything simple. As storage and serving is fully managed by Plugin Manager, it helps us to cache, validate and sanitize user data properly from a single place.

But when we decided to add support for box.net, there comes a challenge. We have asked for username and password for box.net account from our users to pull out the data from their shared folders and files. “PASSWORD” – and that is the thing everyone thinks twice before providing to a third party. Everyone cares about their personal data security.

In MiproApps every data collected from user are submitted to storage service via Ajax request. And we simply cant send plain password collected by users in an Ajax request. What we did in this case is we had signed user’s sensitive information using a 128 bit public key (RSA) in client side. The private key is stored securely in our server and that encrypted information is decrypted only in server side. So client application has just the public key.

Box.net widget in Facebook Fanpages powered by MiproApps
Box.net widget in Facebook Fanpages powered by MiproApps

There were other challenges as well, while we went to implement this encryption in client side by Javascript and Decryption by PHP. Unfortunately PHPs Mcrypt doesnt support RSA, and Zend Framework doesnt provide any component for that. And there was a trick when you encrypt your data in JS. You must add a null byte at the end of your data, otherwise PHP cant decrypt it.

We have used RSA library (a combination of RSA, BigInt and Barett Library) from Ohdave and used the Crypt_RSA library from PEAR. And it also required us to install bigint PECL extension.

You can see some example code at here and you can use the RSA public/private key pair either by openssl shell command or the RSA key generator from ohdave.

The service layer is working smooth. Plugin developers doesnt need to bother about encryption and decryption. Everything was managed transparently under the hood. And so far we are only developing our plugins, data is secured and safe. Users can add their publicly shared box.net files directly in their facebook fanpage. For a sample output, you can check out my page. You will find the box.net component at the bottom right corner.

jQuery:hooking form submit and making it ajax request

modern javascript frameworks are big blessings to every front end developer. they made our life so much easier so that we can sleep more and become fat day by day πŸ˜€ – i am a big fan of jQuery and mootools.

in this post i am going to show you how you can hook a normal form submission process, regardless of it’s method GET or POST, and convert it into an ajax request. the whole process will work dynamically. it will parse form input elements, make a JSON array from them and make an ajax request to the appropriate action url. after that, it will invoke the user supplied callback function.

problem 1: parsing form elements was a small challenge. you can do it in various way (by traversing or serialize or using css selectors). i choose to use serializer routines. jQuery has builtin support for two types of serializing , one is $(form).serialize() and another is $(form).serializeArray(). lets have a look at the output of both of them for the following form

[sourcecode lang=”html”]
<form id="f1" action=’some target’ method=’POST’>
<input type ="textbox" id=’username’ name =’username’ value=’me’/>
<input type ="checkbox" value=1 id=’guests’ name =’guests’/>
</form>
[/sourcecode]

now lets check the output by both serialize() and serializeArray() method

[sourcecode lang=”javascript”]
alert ($(‘#f1’).serialize());
//output is "username=me&guests=1"

alert($(‘#f1’).serializeArray()
//output is [{object},{object}]
[/sourcecode]

are you scared seeing this [object] output of serializeArray()? well dont panic. serializeArray() returns a JSON structure. you can still investigate using toSource() method

[sourcecode lang=”javascript”]
alert($(‘#f1’).serializeArray().toSource()
//output is [{"username":"me"},{"guests":"1"}]
[/sourcecode]

but that will not be usable to send in our AJAX request. we need a JSON array key/value pair (or you can use the output of serialize() function too to send as data in ajax request, the serilizeForm part is completely optional )

lets create a new function called serializeForm which will create JSON key/value pair out of serializeArray() and do the rest of the work.

[sourcecode language=”javascript”]
$.fn.serializeForm = function()
{
data = {};
url = this.attr("action");
items = this.serializeArray();
$.each(items,function(i,item)
{
data[item[‘name’]]=item[‘value’];
}
);
return data;
}
[/sourcecode]

now lets hook the normal submit process of the form using the following hook

[sourcecode lang=”javascript”]
function submitHook(form, callback)
{
$(form).submit(function(e){
items = {};
items = $(form).serializeForm();
url = $(form).attr("action");
if(""==url)
{
alert("Cannot submit form. No action specified");
return false;
}
callback = callback?callback:function(){};
$.post(url,items,callback);
return false;
});
}
[/sourcecode]

now you can just hook the form simply by this

[sourcecode lang=”javascript”]
ourCallback = function (data)
{
alert(data);
}

submitHook($(‘#f1’),ourCallback);
[/sourcecode]

happy jQuerying πŸ™‚

Performance tips for web applications

I have recently came by the article β€œHigh performance websites” in yahoo developer network. This article pointed 13 key points to speed up your application. These are

1. Make Fewer HTTP Requests
2. Use a Content Delivery Network
3. Add an Expires Header
4. Gzip Components
5. Put CSS at the Top
6. Move Scripts to the Bottom
7. Avoid CSS Expressions
8. Make JavaScript and CSS External
9. Reduce DNS Lookups
10. Minify JavaScript
11. Avoid Redirects
12. Remove Duplicate Scripts
13. Configure ETags

I was trying to improve performance for a web application recently keeping them in mind. Let me describe how to do some of them technically.

Making fewer HTTP requests:
Each time file loads from your web server, it generates an http request. So you can reduce number of http requests by caching some contents which are almost static or changes very rarely. if these contents are loaded from browser cache, there will be no request for them over HTTP. You can use apache’s mod_expire module to cache specific tyyou (image, swf etc) of contents in your site. The following line in httpd.conf loads mod_expire successfully.

LoadModule expires_module modules/mod_expires.so

After that, write the following lines in .htaccess to cache all the image, swf and javascripts for one month from the current date, with the help of mod_expire

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/png A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType application/x-javascript A2592000
ExpiresByType application/x-Shockwave-Flash A2592000

If you are confused by the letter “A” with number of seconds associated with it, it actually means “Access time”

For reducing number of HTTP requests, you can also merge all your css files and javascript files into one css and js file.

Use a content delivery network
Yeah, that works really cool. You can serve your static contents more effectively from popular content delivery network (CDN) like akamai or Amazon S3. The benefit of using popular CDNs is that these CDNs are scaled and distributed and really knows how to serve your content faster than ever.

Add an Expiry Header
Expiry tags helps your browser to understand when to invalidate cache for a cached content. So you can ask how to add expiry header to your content. You can do it by injecting HTTP headers while delivering it from your server to end user’s machine i.e browser. Apache’s mod_expire module does the same thing, by MIME type of contents. But it doesn’t help to cache a single file or multiple files. So if you want to cache a specific file, you can do it using following PHP code.

<?php
header("Expires: ".gmdate("D, d M Y H:i:s", time()+600)." GMT");
header("Cache-Control: max-age=600");
?>

This will set the expiry time 600 seconds from the time of content delivered.

Gzip components
While delivering any data from web server to browser, you can apply gzip compression over it. These gzipped data are decompressed when received by brwsers and treated as regular data. Almost all of the modern browsers supports gzip compression. To compress your content, you can do it either automatically using Apache’s mod_deflate or manually via your code. If you like to do it using mod_deflate, then you have to enable mod_deflate first and then modify your .htaccess file to make use of that. The following line in httpd.conf enables mod_deflate with apache

LoadModule deflate_module modules/mod_deflate.so

Now if you want to make use of mod_deflate and compress your content on the fly while delivering, you can add the following line in your .htaccess file.

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-javascript

Or you can write PHP code for delivering gzipped contents. The following piece of code delivers any javascript file as a gzipped one.

<?php
//gzipjs.php
ob_start("ob_gzhandler");
header("Content-type: text/javascript; charset: UTF-8");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 * 24 * 3;
$ExpStr = "Expires: " .
gmdate("D, d M Y H:i:s",
time() + $offset) . " GMT";
header($ExpStr);
include(urldecode($_GET['js']));
?>

To deliver a javascript file (say prototype.js) using gzipjs.php you can load your scripts like this

<script type=”text/javascript” src=”gzipjs.php?js=prototype.js” ></script>

But hey, don’t just include any file passed to it (as i did it here in gzipjs.php). I wrote the code quickly to demonstrate the process. In practice you must (M.U.S.T) sanitize the supplied argument before including. Otherwise it could be a very dangerous security breach.

Minify Javascripts
Minifying means compressing javascripts by removing unnecessary white space, comments and others. You can make use of customized rhino engine which is used by dojo’s shrinksafe. Rhino is a nifty tool for doing these things.

So, how to do it? Download custom_rhino from dojo’s shriksafe page. After that compress your javascripts using following command.

java -jar custom_rhino.jar -c infile.js > outfile.js

That means you must have JRE installed in your machine to execute the command shown above (rhino is developed using java). Now if you have number of script files and you want to compress them all at once, without applying his command for each of them, you can make a nifty batch file to do it for you. Here is the code. It will compress each script files into script.js.packed file.

for /F %%F in ('dir /b *.js') do java -jar custom_rhino.jar -c %%F > %%F.packed 2>&1

Place custom_rhino.jar file and all your script files in same directory and run it. All your scripts will be packed.

I hope these tips will really boost up performance of your web application. This is just a basic article and I didnt go details of these tips. There are also other ways (like javascript on demand) which will also help increasing the performance.

Don’t forget to check other options from the original article at yahoo developer network.

Reference
1. http://betterexplained.com/articles/speed-up-your-javascript-load-time/
2. http://www.fiftyfoureleven.com/weblog/web-development/css/the-definitive-css-gzip-method
3. http://httpd.apache.org/docs/2.0/mod/mod_expires.html
4. http://httpd.apache.org/docs/2.0/mod/mod_deflate.html
5. http://developer.yahoo.com/performance/rules.html

List of RSS Feeds I read almost everyday

I am sharing a list of RSS feeds that I read almost everyday. And which one is my favorites RSS reader? Well, I use GoogleReader because of it’s excellent features like star and feed history. also I like it’s feed sharing feature.

1. Ajaxian : http://www.ajaxian.com/index.xml
2. Cow’s Blog : http://cow.neondragon.net/xml.php
3. IBM Developer Works (Web) : http://www.ibm.com/developerworks/views/web/rss/libraryview.jsp
4. IBM Developer Works (Open Source) : http://www.ibm.com/developerworks/views/opensource/rss/libraryview.jsp
5. Designer Folio : http://feeds.feedburner.com/dezinerfolio
6. Digg Technology : http://digg.com/rss/containertechnology.xml
7. DZone Latest Front Page Links : http://www.dzone.com/feed/frontpage/rss.xml
8. Freelance Switch : http://feeds.feedburner.com/FreelanceSwitch
9. HacksZine : http://hackszine.com/index.xml
10. International PHP Magazine News : http://www.php-mag.net/magphpde/psecom,id,26,noeid,26,.html
11. JSLabs High Performance Web Apps : http://feeds.feedburner.com/jaslabs
12. LifeHack : http://www.lifehack.org/feed/
13. Mashable : http://feeds.feedburner.com/Mashable
14. Maxdesign : http://www.maxdesign.com.au/feed/
15. Newsvine (PHP) : http://www.newsvine.com/_feeds/rss2/tag?id=php&d=v
16. PHP Freaks : http://www.phpfreaks.com/feeds/articles.xml
17. PHP Magazine : http://www.phpmagazine.net/syndicate.xml
18. PHP Coding Practise: http://php-coding-practices.com/feed/
19. PHP Developer : http://phpdeveloper.org/phpdev.rdf
20. PHP Geek : http://www.phpgeek.com/wordpress/feed
21. PHP Architct News : http://www.phparch.com/phpa.rss
22. Planet Ajaxian : http://planet.ajaxian.com/index.xml
23. Planet PHP : http://planet-php.org/rdf/
24. Programmable Web : http://feeds.feedburner.com/ProgrammableWeb
25. ROScripts : http://feeds.feedburner.com/ArticlesAndProgrammingTutorials
26. Sitepoint Blogs : http://www.sitepoint.com/blogs/feed/
27. Sitepoint News : http://www.sitepoint.com/recent.rdf
28. Smashing Magazine : http://www.smashingmagazine.com/wp-rss.php
29. Jonathan Snooks Blog : http://snook.ca/jonathan/index.rdf
30. TechCrunch : http://feeds.feedburner.com/Techcrunch
31. Technorati Javascript Links : http://feeds.technorati.com/search/Javascript
32. Technorati PHP Links: http://feeds.technorati.com/search/PHP
33. Veerle’s Blog : http://feeds.feedburner.com/veerlesblog
34. Web2List : http://feeds.feedburner.com/Web2list
35. Zen Habits : http://feeds.feedburner.com/zenhabits
36. Del.icio.us PHP Tags : http://del.icio.us/rss/tag/php
37. PHPExperts Forum : http://rss.groups.yahoo.com/group/phpexperts/rss
38. 456 Berea Street : http://www.456bereastreet.com/feed.xml
39. Particle Tree : http://feeds.feedburner.com/particletree
40. Simple Bits : http://simplebits.com/xml/rss.xml