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:
- Use JavaScript libraries. They definitely make your work easy!
- 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);
- Use short names for “ContentPlaceHolders”. You can save hundreds of bytes simply by giving short names to your ContentPlaceHolders. Consider that:
- Asp.NET prefixes contentplaceholder’s ID to all the controls kept inside it.
- The new IDs are copied to all javascripts and postback events on the page.
- 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.
- Store objects returned by “$” or “document.getElementById” into a “var”. Avoid tracing the document again-n-again for finding the same element.
- Use objects in javascript.

- 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.
Good luck & try to follow these steps.If you have any doubt,hit me back via comments.
No comments:
Post a Comment