Monday, December 14, 2009

Speedup your page load with Ajax

Sometimes you are stuck with a heavy aspx page, lots of computation is happening at the server side or large database transaction, the bottom line your page takes a long time to load. You can use ajax and WCF to enhance the response perceived by the user as follows.

1- Display the page to the user without any data
2- Show progress indicator telling the user that the page is being prepared
3- Send ajax request to your WCF
4- When data is ready show it to the user


Here is how.
Using Java script call a method on the page load as follows
body onload="onload()"


Implement your onload in a script tag in the header section as follows

function onload() {
var svc = new Ayman();
svc.DoWork("Test", OnGreetingComplete, OnError);
}


create your WCF service by using the template Ajax enabled WCF (you may need to install service pack 1 for VS 2008 if you can not see this template in the add new item dialog box)
then write your service code, something like the following

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Ayman
{
[OperationContract]
[WebGet]
public string DoWork(string str1)
{

Thread.Sleep(1000);
return "Hello";

}


in your script block implement the two functions,

function OnGreetingComplete(result) {

$get("dispGreeting").innerHTML = result;
document.all.Pro.style.display = 'none'
}

function OnError(result) {
alert(result.get_message());
}

note that, I have an html label called dispGreeting and when the Ajax call returns the greeting is displayed to the user. and there is a div called Pro which gets hidden when the Ajax call is completed.

It is interesting that your WCF will also receive all the cookies in the request and if you want to find out what cookies you got you can get the current HttpContext as follows

HttpContext context = HttpContext.Current;

and then browse through your cookies or get a specific cookie as follows
HttpCookie cookie = context.Request.Cookies["YourCookieName"];


to download the code for this post please click this link