Question subject: Client-side Caching using AJAX & Javascript
Posted: Sun Nov 09, 2008 6:39 am
Joined: Tue Nov 06, 2007 2:17 pm Posts: 847 Has thanked: 0 time Have thanks: 1 time
Introduction
This article shows you a useful technique to cache some of that page data on the browser in-memory. Since we use Ajax, the page is not reloaded each time. This prevents the cache from being invalidated on each round-trip. Client-side caching is sometimes required for performance reasons and also to take the load off of the DBMS. Since most modern PCs have plenty of RAM to spare, client-side caching becomes an important weapon in the modern programmer's arsenal of tricks.
With the advent of Ajax, application data can be maintained on the client without the use of ViewStates (aka hidden fields) or to a lesser degree, cookies. As any experienced developer will tell you, ViewState is a double-edged sword. Indiscriminate use of ViewStates can really have a detrimental effect on performance - what with the Viewstate payload ferried to and from the server with every postback.
Screenshot - article1.gifThis begs the question: Can we use this technique without Ajax? AFAIK, the answer is: "No." That is so because we are maintaining the cache as a page-level variable on the client. The moment the page is refreshed via a full-page postback, the cache is invalidated. Keep this in mind while designing your application.
The accompanying code can be extended to use record data too, via Javascript and the presentation logic can also be hived off to a Javascript routine on the client. We could even pipe XML down to the client and it could be parsed and presented through client-side script.
To keep this sample code easy to comprehend, I have rendered the tabular data from within the Web Service itself - which may not be architecturally optimal. Since this is not a treatise on design best-practices, I have taken the liberty of cutting corners here and there for the sake of brevity.
img width="36" height="42" style="float: left;" alt="Screenshot - article1.gif" src="Client-sideCaching/article1.gif" />We use JavaScript associative arrays to maintain our client-side cache. One thing to be noted about JS associative arrays is that once you associate a string key with an array, there is no way to iterate through the array using indexes. Supposing you are using it like this:asarray["akey"] = <value> there is no way you can revert to accessing the elements by their ordinal position like this: var anyvar = asarray[0]. Using the code
Let us examine the critical sections of the code that are absolutely necessary for client-side caching to work. The rest of the code deals with presentation and layout and a discussion on these aspects will be skipped.
For those who subscribe to the view that source-code is the ultimate documentation, you may skip this section. For the others, we'll try to separate the wheat from the chaff. Let us look at the most important pieces of code that makes client-side caching with Ajax and Javascript possible. I am using XML data for demonstration purposes and this makes the project run without having to change connection strings or even having SQL Server installed on your computer. Step 1
Create a New Website and choose "ASP.NET AJAX-Enabled Website". If you do not have .NET 2.0 Ajax Toolkit installed, go here and download them. You cannot begin this exercise without it. Step 2 Select "Add New Item" by right-clicking on the project in Solution Explorer and choose "Web Service". Add the highlighted code to your web service class. The [ScriptService] attribute decoration makes the web service class callable by the Ajax framework. You have to include using System.Web.Script.Services to be able to do that.
IMPORTANT: You must have installed Microsoft ASP.NET Ajax 1.0 and the Ajax Toolkit for this sample to work. Add a reference to AjaxControlToolkit.dll (not included in the distribution) for the code sample to work You will find it here.
Code:
using System.Web.Script.Services; ... [ScriptService] public class DataAccess : System.Web.Services.WebService { ...
Step 3
Flesh out your web method to do something useful. Our example does this:
Code:
[WebMethod] public string FetchOrders(string key) { return LoadData(key);; }
Now, we go to the client script that does the actual caching and retrieves data by making a call to the web service. This employs rudimentary JavaScript - no surprises here.
Code:
var cacheData = new Array(); // This is our cache
var currSel = null; var seedData = "0BFA4D6B-DD18-48aa-A926-B9FD80BFA5B7"; // Prime a cache item with a unique initial value
Step 5
Add the needed JavaScript code now. We have a HTML button with the ID btnFetch. In the OnClick event, we trigger either an Ajax asynchronous call to the server or render from the cache.
Code:
function btnFetch_onclick() { currSel = document.getElementById("dlCustomers").value; var status = document.getElementById("divStatus"); //var svc = new DataAccess();
Screenshot - article1.gifOne point to take careful note of is that if you are using multiple cache arrays in your page, you will have to maintain multiple states for the item currently selected. In that case, you might have additional state variables like currProductSel, currCustSel etc. Of course, you will have to have multiple cache arrays as well Conclusion
If employed correctly, client-side caching can be a great tool to enhance the user experience and make the web application more responsive. If your application is so designed, you may also consider prefetching data through Ajax calls and plonking them into the cache. Prefetching requires minimal code overhead and can be an additional boost to performance if your application warrants it.
_________________ Any help needed just reply to my topic , ccna ,ccnp certified .
rakeshgiri
Question subject: Re: Client-side Caching using AJAX & Javascript
Posted: Sun Aug 29, 2010 10:21 am
Joined: Sun Aug 29, 2010 10:00 am Posts: 3 Has thanked: 0 time Have thanks: 0 time
hi,
i am rakesh giri ,a software developer from india,
i just saw your article on internet regarding using ajax. i am facing some problem and want help.
i hope you will help me
i have a website named 'bizlis.com'which i have built a website in asp.net 2.0 with sql 2005 database.it is a database search engine which searches buyers and sellers all around the world....
my mssql database consist of 267 tables of 267 countries(table names-dbo.india,dbo.australia etc) which contains suppliers/buyers of that particular country/table.which has fields like address,email,website,buyer or seller(cateory) etc. each country table has all the details of buyer or supplier of that country
when user enters url 'bizlis.com'.my home page opens .loading time of home page is fast.homepage has .. user has to select country from dropdown box,he selects category from dropdown(buyer/seller)he then selects a criteria from dropdown(exact phase search,anyword search or all word search) after that he enter product name in the textbox which he wants to search ...after that searching is done ..the problem is that my searching for the first page takes very long time it takes 8-10 seconds (try searching for steel sellers from india as it has maximu records)..after first page is loaded in 9-10 sec ..then 50 records are shown .it has navigation button on click of next navigation button data comes faster as compared to loading(starting first page-which brings data for the first time ) page.yhis is because cahing is applied...
hence now my biggest problem is that how to make my first datapage fast(starting first page-which brings data for the first time)
some of my friends told me to apply pre caching
i can do it in this way
by loading data into cache by country dropdown (when user selects country before pressing on submit button). in this way the table of the country which is selected by user will get loaded.
but in the case of country dropdown cache,user might have to wait for some time after selecting coutry as data will be loaded and he might not be able to select other dropdown such as (all,any,exact search or enter the product name in the text box)
my friends suggested me :pre-caching on the DB tier by using perhaps using Ajax to submit a query before the user hits the submit button.
my main problem is that to avoid waiting for user when data is being loaded .as i want the cache data to be loaded as fast as as possible ..so that user donot have to wait for clicking on next action as data is being loaded in cache
i just saw your article regarding using ajax .i think this thing can help me .
hence can you help me by giving sugesstion/codes about what to do and how to avoid user waiting after dropdown selection as caching is done in backend and user does not face any difficulty in acessing the website (does not have to wait while home page is being loaded(when all tables are cached or does not have to wait after country dropdown is selected)