How can I minimize the weight of my ASP.NET pages? - asp.net

I rely heavily on nested Master Pages in my web portal, this causes ASP.NET to generate huge ID tags for controls it creates, for example:
"ctl00_ctl00_MainBody_ctl00_lblDescription"
for a lblDescription Label i've created.
Is there any way to reduce this clutter?
Any other techniques(sorry for being general) to reduce page weight other than removing the viewstate?

Look at Yslow and do what it tells you (I would start here)
Turn off viewstate
Use jsmin to reduce the size of your JavaScript files
Reduce the size of your CSS (dead link)
Compress your response with standard gzip/deflate compression
Using ASP.NET MVC will give you smaller IDs

Whenever possible use HTML Controls. HTML Controls. They are lighter since don't have server-side objects unless you specify the runat="server" attribute.

I don't know how to remove the client id bloat but some general tips for making your pages smaller would be:
Minify and combine any .js/ .css into one file.
include css at the top of the page and js at the bottom (not really going to make it smaller but UI will load faster)

Enable IIS static/dynamic compression
Use caching for controls and pages
Ajax content loading - it's helps when you want to see main content faster than content with less priority

Terrapin has some great suggestions, but they are pretty idealistic. If you are looking for more applicable solutions to your current situation, check out control adapters.
The CSS Friendly adapters will do a lot of work for you to convert your ASP.NET controls from large ugly, long id named tables into more concise divs, with shorter names.
I have used them in a past and they can really make a huge difference. Other than that, turn the viewstate off on any control that doesn't need it. Conform to proper CSS/HTML and it will make another significant difference.
Best of luck!

To minimize the weight of your ASP.NET pages, you can also override the PageStatePersister property (of the Page class) with SessionPageStatePersister. See example here. That way, the Viewstate will be kept in the Session object on the server side, thus reducing the size of the html page on the client side.

Especially inside repeaters, ListViews and GridViews, name your controls something short.
This should be obvious by the Context (A list of Products)
If you have only one HyperLink inside a repeater, call it hl. You don't need to call these controls HyperLinkProduct.
<asp:Repeater id="rptProducts" runat="server">
<ItemTemplate>
<asp:HyperLink id="hl" runat="server" NavigateUrl='<%# Eval("URL") %>'>
<%# Eval("Name") %>
</asp:HyperLink>
<asp:Image id="img" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' />
</ItemTemplate>
</asp:Repeater>
This will render something like:
<a id="ctl00_rptProducts_ctrl0_hl" href="/products.aspx?id=5">
Product Name
</a>
<img id="ctl00_rptProducts_ctrl0_img" src="images/5.png"/>
Multiply those ID names by a 100, and your IDs start to take up a lot more space if you use long descriptive names. Inside Repeaters, short IDs should be clear enough, if your Repeater is well-named.

Using CSS Sprites can speed up your page by reducing the number of requests. Here are a few articles I found.

In your case of using a label, make sure that you really need to use the label (which generates the text in a <span> tag. You could use a Literal instead.
Set EnableViewState="False" on controls that don't need it (or on the entire page/website)
If you're trying change the obscure ids generated by ASP.NET, there's not much you can do there.

Use html/css to style your pages, avoid tables for layout, when creating a label specify the id, shorter it is, the better.

Turning off the viewstate, as you mention, is good. Also I have noticed that the ASP.NET tree control generates a very large amount of HTML (if you have a fair number of nodes). I ended up writing my own tree control that generates 1/4 the HTML of the standard tree control. So you could look for controls like that, that are especially bad, and write your own control.

I guess if you were desperate to do this without retooling your pages (and none of the other sensible ideas worked ;) ), you could do this:
Write an http module that parses and extracts the ids with shorter, recognizable unique ids on the fly as the page is sent to the client, and store them in an application scope hash table. Then, on the return trip perform the reverse step for the incoming data.
At least, that's what I'd try. I'm not sure how nicely it would play with certain html and/or javascript constructs, but I think it could be done.
I suspect it would be a pain in the butt to do, especially if the shorter unique ids happened to conflict with any legitmate non-id values.
EDIT: Just remembered. You'd need to handle the ViewState too... (that would need to be decoded, fixed and re-encoded. Seems like a lot of trouble :) But then again, if you're going to go to that trouble, you can compress the viewstate a lot better by overriding the load/save viewstate methods...
I cut some huge pages (200K of html) down to about 30K using that method a couple of years back. In fact, using custom compression on the ViewState can often be enough to reduce a page size hugely.

Related

asp:image or img

Does asp:Image tag perform faster than normal HTML img tag?
I have 20 images to show on a web page (tiny images) and I have no idea which one to use.
On server-side
HTML elements in usual use (without setting runat="server" on them) are always faster compared to server-side counterparts, because they don't execute any additional server-side logic or consume other resources. They also don't add anything to page's view state.
On client-side
Simple server-side controls (those that translate to a single HTML element) are no different to normal HTML elements. But complex server-side controls (like calendar) are complex in terms of HTML element quantity thus require some additional browser resources. But making the same thing/functionality with usual HTML would create more or less similar results. So we can assume on the client-side speed is the same.
Verdict
Use server side controls only when you need to add some server-side processing to it. If not, rather use plain-old-HTML-controls. They will be processed faster on the server, will not add anything to view state and will work with the same speed on the client as their server-side counterparts.
This is true for any HTML element that has a server-side equivalent (like img that has asp:Image on the server side). When there's no client-side equivalent (like calendar) you have to of course use server side controls or use some client-side library that provides such functionality (jQuery has a date picker for instance). But you have to know Asp.net processing quite well to combine the two effectively.
use asp:image only if you have to manipulate it on the server side (dynamically setting the title, source, visible, etc).
since asp:image is "running" at the server side, it consumes a bit of memory and cpu usage.
Use an <img /> tag if you don't need to interact with it programmatically. That's less overhead (although the overhead of using asp:Image is minor).
No, there is no performance difference at all when it comes to loading the images. The asp:Image control produces an img tag, so the result that arrives to the browser is more or less identical.
The asp:Image control is convenient if you want to control it's attributes from the code behind.
The img tag will be faster for sure because no server side processing and not have ViewState (which can be disabled still).
Typically if you don't need to set properties dynamically don't use <asp:Image ... />
Remember you can always do something like:
<img src='<%= MyPathMethodInCodeBehind("some value") %>'
alt='<%= MyClass.SomeMethod(someParam) %>' />
However, the difference is really small and would argue it's not notable, yes, even for 20 images.

Is it bad to use runat="server" on <tr>?

I'm supporting an application that uses runat="server" all over the place to show/hide table rows.
For example, in places where there are dependent DropDownLists, the row with the child ddl will be hidden until a value us chosen in the parent ddl.
Is that a bad practice? Is there a better way to do this?
I use runat="server" anytime I need it. So I think you can use it too. :-)
I think that's absolutely terrible practice. First of all you do not need to make the trip to the server to hide and show controls, unless you need new data.
Second, any decent javascript framework will allow you to hide show controls based on the control's id, class name, or whatever css selector. Moreover using a javascript post/get to a generic handler will give you the data that you need without the postback.
I'd suggest using JQuery, or some other alternative.
It depends on how much you care about performance. Anything that is marked with runat="server" goes through more processing than just client side tags.
Personally, I've used them before. Especially in the situation where a table cell or table row is relying on data from the server. You can use Javascript or JQuery with a hidden field but you still have to hit the server for the hidden field, so it doesn't buy much.
It's not bad to use runat="server" with standard HTML controls. Often you'll find the use of PlaceHolders to show and hide content on pages, or in ASP.NET MVC you might see the use of inline code blocks such as <% ... %> within the views. On it's own and not in consideration of other design aspects, it's neither good nor bad.
That's what I do to hide the row containing other server controls. The other options are to use a asp:panel or other container, but that will add more HTML without any gain.
I don't think it's necessarily bad practice. I've done the very same thing plenty of times. I think it's mainly personal preference.
Not at all. ASP.NET supports making any html tag run on the server side. Your alternative is to wrap the tag in a Panel, and hide or show that. If you're not looking for the extra functionality or want to control the output yourself, making an html tag run on the server isn't a problem.

ASP.NET - improve performance

Is there any reason use standart HTML controls (input type=text,input type=checkbox) instead of asp.net controls ( asp:TextBox, asp:CheckBox) to improve performance?
IMHO this would be a micro optimization. You will gain performance but it won't be noticeable. On the other hand you will loose much of the flexibility offered by the server controls.
You could try to reduce the size of the ViewState by disabling it for controls that don't need it. This will reduce the size of the generated pages and improve performance.
The ASP.NET user controls will all have ViewState associated with them unless you explicitly set
EnableViewState="False"
As such, you will bloat the size of the underlying page if you have a large number of controls. As a general rule, use what meets your needs and nothing more.
Do you need to access the user control in the code-behind?
Do you need the control to maintain value across post-backs etc?
In most cases, it won't make a difference, but it is good to keep your page clean if you don't need these features.
As always with performance optimizations: it depends on the situation. Test it in your project and see if it makes any difference.
Also with .net 4.0 another con of using server controls is gone, since you can set ClientIDMode to Static, which will give you full control over ID's on your controls. Previously using just a standard textbox or button (without viewstate) would still render crazy non-readable ID's because of the way Naming Containers work. Those days are over now though :)
Remember your three options are:
use regular html which can't be referenced on the server.
add runat="server" to your existing html-tags (ie. ) and you'll be able to access it as an HtmlControl.
use the asp.net tags (<asp:* runat="server" />)
The disadvantage of option 3 is that you don't always know what the rendered html-markup will be and you have less control over it. I personally only use option 3 for more advanced controls like , the button () and third party controls. For normal html-markup that I need to reference on the server I prefer option 2.
Regarding performance I would mainly look at the rendered output, how much extra bloat is rendered to the client and such. CPU-time on the server using one or the other approach I would say is secondary compared to the different caching techniques ASP.Net has already.

What is affected in the Page/Control life cycle when an asp.net control has no ID

If in the markup you declare a control like this:
<asp:Label runat="server" AssociatedControlID="txtSomeInput">Some Input:</asp:Label>
<asp:Textbox id="txtSomeInput" runat="server" />
Does leaving out the ID from the label control change anything in regards to Viewstate or the Page/Control life cycle? Does it just get some generated ID? Obviously it cannot be referenced in the code-behind at design time (well at least not by the programmer)...Just curious as to if this has any side effects (or tangible benefits)?
Further, I would presume if this control cannot be referenced at design time it can't really be changed in a way that would add any information to viewstate...yet the runat tag allows the AssociatedControlID to be decided (master page crap ids for example) thus not having to have a html label with a <%# %> to write the clientId??
thanks!
It makes no difference from a functionality perspective. Elements which require an ID to function properly will auto-generate one. It does make referencing the control by name in the code-behind difficult, but still possible, it just requires manually finding it and wiring it.
Some side-effects are if you're using some tools that run script client-side. For example, a button without an ID cannot properly trigger an update panel operation correctly (in most cases) because when the javascript is created rendering what clicks should be captured/re-routed as partial postbacks...the lack of an ID leaves it out of the list (Think, what javascript could you manually run to attach the handler without it?).
The button just needs the right click handler, the ID doesn't matter for what it triggers server-side...but this leaves client-script needing more a lot of times.
As a side note: If you haven't looked at .Net 4, I suggest you take a look, the situation has vastly improved with ClientIDs.

Which is better to initialize HTML control values: Javascript or inline server tags?

Which is better/more maintainable, using Javascript to initialize the values of the different HTML controls or writing inline <% %> tags?
The current page I am writing has many HTML controls and I'm afreaid that putting inline ASP would make it too unmaintainable.
Well... using JS to populate the controls with values will make the whole solution useless in JS-free environments. This is not what the webdev community calls unobtrussive.
As you donĀ“t define better any better (!) I would say go for the inline rendering.
If you really have millions (I really doubt this number) of HTML Controls in your page I would say you need to get back to the drawing board and re-architect the solution.
You are going to have the same problem regardless of the method: maintainability.
I have some legacy forms that need to remember some fields between calls, so I have a lot of code that might be a little ugly, but if you stick to a standard, doesn't get too messy.
<label for="email<%=i%>">E-Mail<% if required then %> (*)<% end if %>:</label>
<input name="email<%=i%>" id="email<%=i%>" type="text" value="<%=Trim(request.form("email"&i))%>" />
The problem is that it involves a lot of copy paste when having to add a new control. You could make a function to build it and keep the code duplication to a minimum.
<%= BuildHTMLInputControl("email"&i, "text", "E-Mail", true) %>
' Response: <label for="email1">E-Mail (*):</label><input name="email1" id="email1" type="text" value="Previous Value" />
I haven't done something like this, because it hasn't been a concern yet in the small forms that I've done this.
The advantage of this is that the fields are populated onload, there is no flashing of content and you are really friendly to non-Javascript users, something that you should be.
The only difference would be that with javascript youd have a lot of document.getElementById() at the beggining (or rather end) of the document, that increases the HTML file size (which might be a concern) and could not populate the fields instantly.
If you've really got loads and loads of HTML controls in an ASP.Net page, you might have to rethink your design. Why aren't you using server controls?
However, you can always use the runtat="server" attribute on HTML elements to effectively turn them into server-side controls. You can then work with them in much the same way as ASP.Net controls. You may want to watch out for extra Viewstate being added, though.
What is better/more maintainable,
using Javascript to initialize the
values of the different HTML controls
or writing inline <% %> tags?
I wouldn't do it either way. That sounds like old-style ASP, or maybe PHP or JSP-type logic.
The ASP.NET model is to use controls on the page, and then to set the values of those controls either from code-behind or in-line code, possibly using some type of data binding. Separating the display logic from the data is much, much easier to maintain.

Resources