Jonas Stawski

Everything .NET and More

Where Should the Script Manager Live?

I often get asked the question of where should the Script Manager for the ASP.NET Ajax framework live. MY answer is always the same: depends. Why does it depend? Because it really varies from application to application and it is also a personal choice. If you have an application that uses Ajax or the ASP.NET Ajax JavaScript library on almost every page then you can add it to the Master Page. Doing this will alleviate the repetitive need to add it to every page and makes possible future maintenance easier. Also some pages might need to access a web service through the Script Manager and for that you need to register it. You don't want to do so in the Master Page as this will do it for every page. Some people might argue that there is nothing wrong with that, but I will fight to death that there is. The reason you shouldn't do that is the same reason why Windows now comes with a lot of features turned off. And the reason why Microsoft now does this is because it is one of the tenants of a secured application: off by default. You shouldn't expose your app to possible future attacks when there's no reason for it. So to get back in track again, if you do need to change any of the properties of the Script Manager then you can easily do so on a page by page basis by getting a reference to the Page's script manager:

ScriptManager sm = ScriptManager.GetCurrent(this);

Doing so gives you a reference to the Page's Script Manager and now you can change it's properties at run time. Do not forget to check for null (just in case).

So if that is the case then why shouldn't I include the Script Manager in the Master Page no matter whether I will use it or not. The reason why you shouldn't include it is because when you add the Script Manager ASP.NET adds a couple of references to some JS libraries. Those JS libraries are the ones that make ASP.NET Ajax work. By adding those JS libraries to the page you're also generating extra requests and also more data needs to travel through the pipe. So it really doesn't make sense to have the Script Manager in a page where you're not going to use it. It adds overhead.

So how about if I have an application where I use the Script Manager 90% of the time? I'm really adding unnecessary overhead to 10% of the pages. Well it's really not a matter of black and white and that's why I mentioned my answer is always "depends." Maybe those 10% pages equate to 70% of your traffic/bandwidth. In that case then you need to stop and think whether it's worth it or not and like almost every decision that we need to make in software development we have to measure the pros and cons.

Happy Programming!

Add comment