CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Tips for using jQuery in ASP.NET (MVC) applications

By Abhijit Shah
Posted On Sep 28, 2010
Article Rating:
Be first to rate
this article.
No of Comments: 0
Category: ASP.Net/jQuery
Print this article.

Tips for using jQuery in ASP.NET (MVC) applications                    

In this article I shall try to provide few tips on using jQuery with ASP.NET /MVC application.

1.      Always reference the latest version of jQuery the master page of your application. For downloading the latest version of jQuery check the following URL.

http://docs.jquery.com/Downloading_jQuery

2.      Always use the minified version of jQuery. The size of minified version (1.3) is 18KB as compared to 114 Kb of regular version.

Following are the tools available for minifying the application specific JavaScript files

1)      YUI:      http://developer.yahoo.com/yui/compressor/

2)      Jsobf : http://timwhitlock.info/blog/2008/09/07/jsfmt-and-jsobf-available-for-download/

3)      Jsmin : http://www.crockford.com/javascript/jsmin.html

Note: There are many more similar tools available in the market.

3.      Consider loading the jQuery framework files from the content delivery network provided by Google, Microsoft, Yahoo or jQuery as it offers several benefits

1)      It will ascertain that your application uses latest version of the jQuery framework.

2)      Reduce Latency: It reduces the load on your application server and saves bandwidth.

3)      Caching: It improves the response time of your page and jQuery framework loads faster.

4)      If multiple sites are using the jQuery framework from CDN then the same cached version of the jQuery framework gets used.

The Location of CDN for jQuery can be found at below location

Microsoft: http://www.asp.net/ajaxlibrary/CDNjQueryUI185.ashx

Google: http://code.google.com/apis/libraries/devguide.html#jquery

With version jQuery 1.4 onwards we have also get an ability to mention the failover location of the CDN so that in case if the external link of jQuery does not work the file still gets loaded from the internal server.

4.      Always follow unobtrusive way of programming the JavaScript code .i.e. Use a set of principles for writing accessible, maintainable JavaScript. jQuery supports unobtrusive way of Java script programming.  (To know more about Unobtrusive JavaScript refer following URL: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript )

1)      Build a site with plain HTML and follow XHTML standards.

2)      Add Css classes in a separate style sheet file and apply the visual design uniformly to the entire site.

3)      Add an external JavaScript file to the website to provide enhanced site behavior and user experience.

5.      jQuery (document).ready() executes as soon as the DOM is ready. There are multiple ways of coding for this event. The short hand way of using same code is $(function() . You can have multiple instances of this function across js files and all of them will get executed when the document is ready.

6.      Like any other programming language always define and follow the programming standards for jQuery scripting.

7.      Do not write inline client side code (scripts) in the aspx pages. JavaScript or jQuery code should always be written in the .js file and it should be linked in the (aspx or) master page of the application.

8.      If you are using the same selector multiple times they do cache it.

9.      Use jQuery method chaining feature for shorter and clean code.

10.  Scripts should be referenced in the end of the page (before closing the body tag) for better user experience during page load.

11.  Be careful while using the eval() function available in JavaScript. This function is considered to be unsafe (code injection) and performance intensive.

12.  Register and initialize the events properly in jQuery. Always use .live based event declaration for DOM elements. Normal events don’t fire when the parts of pages are loaded using the Ajax calls.

13.  Many times we have some requirement to store some miscellaneous data in DOM structure. Normally we tend to use the attributes tag and add custom attributes to the elements to store the data. But, this is illegal. jQuery provides a way to store state data in DOM which is stored as Data. This can be done as  

1)      SET:      $(‘.SelectorID’).data(‘Key’, value);   

2)      GET:   var temp = $(‘.SelectorID’).data(‘Key’);

3)      Remove:  $().removeData(element) can be used to remove the element

14.  On click of link on few pages we observe that the page scrolls up to the top of the page. This problem can be fixed using simple jQuery trick. Following code overrides the default behavior and retains the cursor position.

Sample Code:

$('#close').click(function(e){    

    return false;  

}); 

            Instead of “ return false “ we can also use e.preventDefault();  

15.  Consider the usage of client side templates for UI where possible as it helps to prevent duplication of scripts, thus reducing the lines of code. Also remember that there could be some risks while using client side templates like

1)      Security threat – injection attacks.

2)      Assumption of the computing power of the client machine

Check out following link for jQuery’s Client side templating engine: http://plugins.jquery.com/project/jqote2

16.  Consider using JSON object for passing server side data to client (browsers). jQuery has got few inbuilt methods that help in parsing the Json objects. This will reduce the amount of data that gets passed from server to client.

17.  Always link the Css file in the top of HTML page in the body tag.

18.  Always follow the single responsibility design principles while writing the scripts. Any jQuery function that we write should be independently testable. This makes the code maintainable, testable and reusable.

19.  Manage your jQuery code properly. Always have different sections in the .js file for Constants declarations, common utility functions, independent reusable functions, event declaration and initialization blocks, ajax call related global reusable functions etc.

20.  For making ajax calls follow a standard common template and reuse it across the application. The template should have provision for request type, Get or post, URL, request data, request format, Success and Failure event declarations and guard functionality implementation. Sample code:

       $.ajax({

         type: 'POST',

         url: url,

         data: data,

         success: success,

         dataType: dataType

       });

 

21.  Do not write long jQuery functions which are difficult to understand. If the function goes beyond 15-20 lines consider breaking it into 2 small functions, follow single responsibility principal.

22.  Use the correct jQuery selectors consistently in all functions.

23.  Use CSS classes in the HTML code for different elements and reference CSS class name wherever required from the jQuery code to access the set of similar elements.

24.  Do not hardcode literals in the reusable jQuery functions /code.

25.  jQuery is extensible. Try converting the reusable block of code into JQuery plugins if possible. Always check if any of the existing plug-in already available on the JQuery site can be reused.  If using readymade code blocks, always understand the complete code before using it as is. If the code does not satisfy exact requirements you may want to write new plug-in for the requirement. There is a large library of JQuery plug-ins available in the market.




26.  Use Fiddler (For IE) or Firebug (for Firefox) to analyze/debug the jQuery /JavaScript.

27.  For implementation of Ajax features, using Update Panes/Script manager should be avoided. Though it provides out of the box Ajax features it leads to performance overheads by adding lot of hidden on the page. JQuery provides easy ways for implementation of Ajax features. Json based ajax requests using jQuery can be light weight and simple.

Simple examples are as follows

1)     jQuery.ajax(options) - low level control

2)     jQuery('div#news').load('/news.html');

3)     jQuery.get(url, [data], [callback])

4)     jQuery.post(url, [data], [callback], [type])

5)     jQuery.getJSON(url, [data], [callback])

6)     jQuery.getScript(url, [data], [callback])

 

Ajax global events

1.     .ajaxComplete(function() { })

2.     .ajaxError(function() { })

3.     .ajaxSend(function() { })

4.     .ajaxStart(function() { })

5.     .ajaxStop(function() { })

.ajaxSuccess(function() { })

 

 

28.  Internet Explorer always caches Ajax calls while other browsers behave differently. It is always better to specify if we want the requests to be cached or not. This can be done as follows,

$.ajaxSetup ({  

    cache: false 

}); 

29.  Prefer using the ID based selectors where possible. The ID based selector uses the browsers internal  getElementById() method. For the class based selected jQuery seems to traverse the DOM structure in IE browser. The ID based selectors can be expected to perform better.

30.  It is good to follow the test driven development approach while programming. For jQuery consider QUnit. It is a powerful, easy-to-use, JavaScript test suite.

31.  The jQuery UI library is great. But reconsider and re-evaluate the need of this before including this library into your application. Many features that you may need could be easily available in base jQuery framework and you may not require including the big jQuery UI library additionally.

32.  Debug logging with IE – The internet explorer developer and Firebug Lite are two tools that are very useful while working with jQuery in IE browser.

The default logging support in jQuery uses Console object. The console object is available in Firefox and Chrome. For other browsers we need to extend the jQuery.Log function and provide our own implementation. This can be easily achieved by writing the debug information straight on the application window.

Following script will do the needful for enabling the default logging function provided by jQuery with IE. Here, for IE, the log will be written in a text area within the application window.

        var debug = true;

        jQuery.extend({

            log: function(msg) {

                if (debug) {

                    if (window.console) {

                        // Firefox & Google Chrome

                        console.log(msg);

                    }

                    else {

              var ta = '<textarea rows="20" cols="100" id="ta" />';

    if ($('#ta').length == 0) {

        $('body').append(ta);

       }

    var t = $('#ta');

    var s = t.val();

 t.val(s + msg);              

     }                    return true;

                }

            }

        });

 

jQuery is a powerful language. It has got lot of features and integrates well with ASP.NET MVC architecture. It will be worth considering the usage of jQuery while building interactive, powerful and responsive web applications.

References

1.      jQuery Website

 http://jquery.com/

2.      jQuery Selectors

http://api.jquery.com/category/selectors/

3.      jQuery UI library Home

http://jqueryui.com/home

4.      Visual cheat sheet can be found at

http://woork.blogspot.com/2009/09/jquery-visual-cheat-sheet.html

5.      Best collection of top jQuery sites with tutorials, samples, articles and discussions

http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-tutorials-tips-tricks-techniques-to-improve-performance/#comment-115

6.      Unobtrusive JavaScript : http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

7.      Five ways of making Ajax calls from jQuery http://www.codeproject.com/KB/ajax/JQAJAXFiveCalls.aspx

 

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments