|
Dynamically inserting JavaScript with RegisterClientScriptInclude (ASP.NET) |
|
|
Written by: Evan Cummings
Dynamically inserting JavaScript with RegisterClientScriptIncludeASP.NET offers programmers a wealth of options and features to provide users with deep and interactive data-driven applications. As its name implies, this functionality is made possible due to the server it resides on. As ASP.NET developers, we are (for the most part) restricted to working exclusively on the server end - the client is fairly well protected from us accessing their machine. This works well most of the time - but what about when we want to harness the power of the users browser or computer? This is an arena that JavaScript has reigned supreme over for a number of years. While the two technologies are seperate in their own right, we can use the .NET library to mix these two technologies together, allowing us to programmtically utilize JavaScript functionality in our ASP.NET code-behinds.
A project I recently worked on decided very late in the project lifecycle that the free Google Analytics service was to be included on every page in our application. At this point we were looking at a fairly intensive manual process to update all of our pages - and possibly even worse was that there was not a real intuitive way to safe-guard this in the future. The .NET 2.0 framework has some great features, however, to help us fix this problem.
The first thing we could do would be to include the JavaScript function in the MasterPage source - this would then make every page implementing the MasterPage to automatically have the Google JavaScript function. This method works, but there is another way that I prefer that gives us some more flexibility and safety in implementing this.
It is considered good form to include JavaScript functions in seperate .js files rather than directly on the page. This gives us a central location in which we can maintain our JavaScript and also support global functionality with it. In the GoogleAnalytics problem, I simply saved the Google provided script out into its own JavaScript file, Analytics.js. Now, in our MasterPage Page_Load() event, we include this bit of code:
Page.ClientScript.RegisterClientScriptInclude("analyticsKey", "Analytics.js")
RegisterClientScriptInclude dynamically inserts the provided JavaScript function into a particular page. Because we are doing this in our MasterPage, all pages implementing it will automatically receive this script. Maintenance is a snap as we only have to edit our Analytics.js file. To utilize this function, we simply provide a key-value pair - a key (as a unique identifier) and the name of our JavaScript file. This method saved my team a lot of time and busy work, and it is far less prone to error.
|
|
|
|
|
|