Wednesday, March 21, 2012

Need Opinion

Hello all, =)

I have question(s) regarding the way I add JavaScript functions and I need opinion(s). Here's one of my example:

HTML:
...
<asp:TextBox ID="txtUserName" MaxLength="30" runat="server" />
<asp:Button ID="btnAddUser" Text="Add User" OnClientClick="return ValidateUser();" OnClick="AddUser" runat="server" /
Code Behind:
protected void Page_Load(object sender, eventargs e)
{
LoadMy_JavaScripts();
}

private void LoadMy_JavaScripts()
{
string script = "";
script += "function ValidateUser()";
script += "{ ";
script += " do something here ...";
script += "}";

System.Web.UI.ScriptManager.RegisterClientScriptBlock( ... ... );
}

As you can see how I register my javascript functions. Most my pages, LoadMy_JavaScripts() contains more than 20+ javascript functions. Every time when there's a postback (partial or not), this LoadMy_JavaScritps() is called again. I have developed more than 100+ pages of .aspx with ajax and all of them are working fine with the way I am doing.

Now I am wondering if what I am doing is right or not. I know that I can add the .js file directly to the ScriptManager using ScriptReference.

from the example above: if i move that ValidateUser function into a .js file, when should i add the .js file to the scriptmanager? Is it at Page_Load? I do not want to add it directly to the <asp:ScriptManager ... > because other pages do not use this function.

Any feedback/opinion would be sweet ... ta ta ...

The 'best practice' on this is to put all your .js in a separate file (or files as needed) and then add them as scriptreferences. THis makes them easier to control and maintain, lets your clients' browsers cache the information, stops you from having to resend the same stuff on every page_load, and so on.

If your scriptmanager is on a Master page (as you indicate) then you use a scriptmanagerproxy on the content page to load additional page-specific script files. ALternatively, you can add a scriptreference programmatically if you want. Embedding javascript in your codefile is a lot more prone to error, no matter how good you are it's easy to forget to add an important syntax bit when you're doing string concatenation.

As a sidenote, when you must concatenate strings, it's almost always a good deal more efficient to use the a StringBuilder object than it is to do += style string concatenation.


Paul,

thanks again, ... i don't have any problem with string concat. =) ... javascript is easy to debug anyway.

Thanks for your input ... before i used to add the javascript druing databound later on i moved everything to a function as i am doing right now. I guess I'll start storing them in a .js file. It makes more sense ... ... =)


Anytime; glad to help. FWIW, I used to do string concat that way too until I heard about the performance hit, which I gather can be pretty signficant if there are enough concatenations.

No comments:

Post a Comment