in .NET

Asp.NET & Javascript –Combo Tips!

Asp.NET & Javascript –Combo Tips!

Hope you all love the pretty work we do with javascript and Asp.NET together. Here are few points to always keep in mind while using the combo:

  1. Use JavaScript libraries. They definitely make your work easy!
  2. Always use “ServerControl.ClientID” property to read client IDs of server controls. Never hardcode IDs. Some of us have already faced the resulting issues…so better be safe!
    If you need to use the client ID in separate javascript files, you may pass client IDs as an object from the aspx page .
    Ex: var options = {txtNameClientID: <%= txtName.ClientID %>};
    You can read the above “options” in your js file as:
    Ex: $(‘#’ + options.txtNameClientID);
  3. Use short names for “ContentPlaceHolders”. You can save hundreds of bytes simply by giving short names to your ContentPlaceHolders. Consider that:
    1. Asp.NET prefixes contentplaceholder’s ID to all the controls kept inside it.
    2. The new IDs are copied to all javascripts and postback events on the page.
  4. Use ‘$’ method. Prefer to use “$” method provided by various javascript libraries or create a little “$F” method for yourself. ‘$’ is far more powerfull with its selectors than “document.getElementById” and it saves bytes too.
  5. Store objects returned by “$” or “document.getElementById” into a “var”. Avoid tracing the document again-n-again for finding the same element.
  6. Use objects in javascript. :)
  7. Use short prefixes. Ever thought we can keep all our prefixes to just “t” instead of “txt”, “l” instead of “lbl”, “d” instead of “div”? Try keeping the prefix length of to a minimum.
  8. Try n keep all js external.
  9. Don’t assign methods in html “<a href=’doSomething’…”. Instead, render clean html and bind events to it using jquery (or any library) “selectors” and “for/each” methods. Alternatively you may also render a javascript array of “ids” to bind the function to.
  10. Use JSON Serialization. Avoid manually constructing javascript arrays/objects using StringBuilder in code behind as it is tedious and unnecessary effort.
  11. Lazy load contents. Reduce page load by lazy loading extra static content. Extra content can be the html which is “displayed-none” by default on your pages.
  12. Put Js calls in the end. Move all “<script src=….>” to the end of your html –right before ending body tag. Even better if you can lazy load your scripts to reduce initial page load.

Thanks & Regards,

Apurv Anchliya