Thursday, April 10, 2008

WebControl - Embed javascript in control

I had to build a custom control which had to use javascript on the borwser and change some setting. For this, I used the clientscripts.register... methods to emit the javascript to the browser. I was not happy about this because it meant that every page will now need to emit the same code and it is not cached. So I thought of using a .js file with the same javascript code and register that within the control. But now the issue was the path of the .js file. I wanted a generic solution where the project consuming this control need not worry about where the js files needs to be picked from. That is when I came to know about embedding .js files into web controls.

Use these statement to do it and you will no longer need to distribute the .js file with your control

If Not Me.Page.ClientScript.IsClientScriptIncludeRegistered("ControlsCommon.js") Then
Dim lstrScriptLocation As String = Page.ClientScript.GetWebResourceUrl(Me.GetType(), "ControlsCommon.js")
Page.ClientScript.RegisterClientScriptInclude("ControlsCommon.js", lstrScriptLocation)
End if

where ControlsCommon.js is the file that I need to include and it resides in the same directory where the controls is present (in the development environment). No need for this .js file when the control is consumed in another project

No comments:

Post a Comment