Working with ASP.Net and jQuery for High Performance AJAX
Back in 1995 when the web took off, the modems worked at 28.8 kbps. CSS was just about invented, most of the scripting was done through CGI, and we streaming video was a pipe-dream. The web-developers were pressed to save every single kilobyte they could to make the website that tiny bit faster.
Now we have 2 MBPs connections at home, streaming DVD quality video, interactive and complex websites. You would hope that all this progress should make a programmer’s life easier, but apparently not. We are still trying to shave off every single KB that we can, and it certainly is not easier.
Ajax – Performance, Can’t have one without the other.
In my opinion Ajax and performance are the same thing named differently. Ajax is such a superb invention because it makes the web faster and easier for use for everybody. Before Ajax when users clicked on a button they would expect the entire page to refresh and the data to reload. That’s at least 20 seconds wasted at each click. Ajax loads only the relevant parts of the page, and people get a higher-performance experience.
But without a fast Internet connection and a good server to process all those requests, Ajax can’t work. A button that makes you wait 10 seconds is worse than a page refresh. That’s why it is vital to think about performance very seriously if you are going to make your website a RIA (Rich Internet Application).
Where does jQuery fit in?
In the early Ajax years it was so awesome because implementing it was so darned hard. Only the top guys like Google had Ajax working well and the rest of us looked on with admiration. It is much easier now because Ajax is an integral part of every development toolkit, and Javascript libraries like jQuery make Ajax so much easier to implement.
jQuery is today the most popular Javascript library because of its innovative CSS selector system, a large plugin repository, extensions and a robust architecture. It is also updated quite regularly and you can easily find articles and tips and tricks for it.
Using jQuery you can not only speed up your Ajax development, but also deliver a better performing Ajax experience. jQuery fits perfectly with ASP.Net. In fact Microsoft has made it an important part of its Ajax strategy as is evident from the fact that jQuery is shipped in the box with ASP.Net MVC, with Visual Studio and is available from the Microsoft CDN (Content Delivery Network) online.
What are the performance bottlenecks for Ajax?
There are three kind of performance bottlenecks that can slow down your Ajax application.
- Slow Server Side Processing
- High size of content (images, video, text, etc.)
- Low-performance client-side Javascript code.
To make a high-performance Ajax website all of these three bottlenecks should be eliminated. In this article while we will focus primarily on the client-side through jQuery, but we will be talking about all of these factors and learn in context how small improvements can make Ajax a better experience.
I am going to assume that you have at least beginner level knowledge of ASP.Net and jQuery. So while I will make an effort to keep things simple and include some information for the newcomers, I won’t be focusing heavily on the basics.
jQuery and Partial Page Updation
Ajax is now a misnomer. It is supposed to mean Asynchronous Javascript and XML, but XML is now an optional part. It would be technically more accurate to call it Partial-Page Updation by Javascript, but PAPUJ does not have the same ring to it.
Partial Page Updation is the anti-thesis of page-refresh. It means loading only that specific portion of the page that needs updation while keeping everything else static. Unfortunately not all Ajax works that way. Take the ASP.Net UpdatePanel control for example. It’s so easy to use and so inefficient that it’s frightful.
When you use an UpdatePanel the server makes the complete page instance and even though you show only the useful bits you go through the entire page load cycle. It’s slow!
Fetching Content With jQuery
With jQuery you can load only the relevant bits but you will have to change the way you work with ASP.Net. Let’s visit our options.
· $.get() – For Get requests to webpages.
· $.post() – For Put requests to webpages.
· $.load() – To load HTML content into a block.
· $.ajax() – To send an Ajax request to the server.
· $.getJSON() – Retrieve JSON data from the server.
· $.getScript() – Retrieve and execute Javascript.
Some of these functions are used very often like $.get(), $.post() and $.load(). Sometimes you may also have to use the $.ajax() function when you need to set up a Ajax request with special features. The $.getJSON() and $.getScript() are special functions used when you want to return a JSON object from the server and for when you want to load and run Javascript respectively.
There are a number of ways you can load data from the server using jQuery. Let’s have a quick look at some of them and discuss their merits-demerits.
1. Separate Pages for Ajax Content
In this method you will create a separate .aspx web page for each part of your main-webpage that you want to implement Ajax on. I.e. you will create a new web-page for each block that you want to update using Ajax.
For example let’s display the stock-quote for our company on the frontpage in a <div> element with the id myDiv. Here’s the code I can call to update it if my latest stock-quote is in a file called Ajax.aspx:
$("#myDiv").load('Ajax.aspx');
Or
$.get('Ajax.aspx', function(data) {
$("# myDiv").html(data);
});
Or
$.ajax({url:'Ajax.aspx',
success:function(data){
$("#myDiv").html(data)
}
});
At the server end the code could look like this:
Designer
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Ajax.aspx.cs" Inherits="jQueryTest.Ajax" %>
<asp:label id="lblAj" runat="server">Stock</asp:label>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
lblAj.Text = "$42.5";
}
The method shown above is easy and quick to implement, but because the page goes through the entire life cycle and we are using ASP.Net server controls, it is not terribly efficient. This should be used when you want to update sizeable chunks of the page and not tiny bits of data because the page-cycle cost will be offset by the amount of data you’re retrieving.
2. Separate .aspx Page with Routing
If you have a lot of Ajax in your website things could become a bit messy if you kept creating separate page for each tiny bit of Ajax. To organize things a little better you can create .aspx pages that serve multiple functions through routing.
In this strategy you call the page with a querystring variable that specifies what function you want.
$('#btnAj').click(function() {
$("#myDiv").load('Ajax.aspx?func=getstockquote');
});
Or
$('#btnAj').click(function() {
$.get('Ajax.aspx', { func: 'getstockqoute' },
function(data) {
$('#myDiv').html(data);
});
});
Or
$('#btnAj').click(function() {
$.get('Ajax.aspx?func=getstockquote',
function(data) {
$('#myDiv').html(data);
});
}
Then you use the Page_Load event of the page to load the appropriate data/usercontrol based on the querystring you received.
3. Accessing Content Through Web-Services
The above two methods that I just outlined are fine for loading content, but what if you want to retrieve actual data or values. Going through a page life-cycle, and routing to just load a couple of variables is overkill and inefficient so we need to graduate to the next level – web services.
ASP.Net services can’t be called easily from Javascript because they are SOAP based. The easiest way to link to them is to use Microsoft Ajax (now improved!) to connect to the webservice. For a small download footprint they make working with webservices extremely easy.
To use web services through Microsoft Ajax put a reference to the Microsoft ScriptManager control and declare each Webservice in the ScriptManager.
<asp:scriptmanager runat="”server”" id="”scriptManager”">
<Services>
<asp:ServiceReference path=”WebService/Webservice.asmx” />
</Services>
</asp:scriptmanager>
The reference to the Webservice has to be inserted within <Services> tag through a <asp:ServiceReference>. Now you can call the method from your javascript code as if it was a Static method of the webservice.
<script type="text/javascript">
function GetMeSomeService() {
alert(Webservice.CallMe(var1, var2));
}
</script>
This is an efficient method of getting data from a webservice, but it adds the extra burden of MS Ajax to your website. Since we are trying to make the most efficient website possible, let’s find a way to call the web-service without MS Ajax.
Calling a Web-service through jQuery
You can call a webservice function from jQuery too, but it’s a lot more harder and lot less fun. Here’s how you can do that.
- Decorate your web-service / pagemethod with the [WebMethod] attribute so that they serialize to JSON (jQuery does not support WSDL).
- Make only POST requests.
- Send an empty JSON variable to the web service if you don’t have any arguments.
The $.ajax function of jQuery can be used to make the request at the client end. Here’s a sample
$.ajax({ url: "/webservice.asmx/DoSomething",
type: "post",
data: "{}",
contentType: "applicatin/json; charset=utf-8",
dataType: "json",
success: function(result) {
alert(msg.d);
},
error: function(err) {
alert("error!");
}
});
Notice that in the success callback function we the reference is to msg.d and not to the msg itself. This is because ASP.Net wraps the JSON serialized data in a variable called ‘d’. It’s a convention to improve data security.
Now Some Tips
In my opinion jQuery shouldn’t be treated as a complement to MS Ajax. It should be treated as a replacement. If you are really intent on maximizing your website’s performance elect to fetch data from your webservices directly instead of MS Ajax which will add another 100 KBs to your webpage.
Here are some tips to increase your website’s jQuery performance even further.
- Link to Google CDN instead of uploading jQuery to your website. Most websites (including Google) is doing that these days so if your user has been to one of them he won’t need to download jQuery again as it will arrive from the browser cache.
- Fetch HTML content when you can instead of getting Javascript arrays and structures. You can just load the content in the div using jQuery functions. This is easy and fast.
- Load only the relevant content. Do not load more than what you need to show. In fact try to keep all retrieved data to the minimum possible.
- Do not use inline styles. Using inline styles will bulk up your returned html data. Try to use an external CSS stylesheet instead of inline styles.
- Keep your Server side code slim. If your server-side code is not efficient it won’t help. So always keep your database optimized and indexed.
- Use UI indications to tell your user that something is happening in the background. An ajax wait animation or a progress bar is great for improving perceived performance.
|