Embedding a JavaScript File as a Resource

Last few days I was on vacation, last day I joined back in my company @ Kerala, and now I am assigned to a ASP.Net application. In the current application, I have to create a web custom control, and in that I need to write some javascript code, and I planned to write the script in the RenderContentsmethod. But when the size of the script was increased, I need to each and every line of javascript using WriteLine method, and it is visible to the user via View Sourceoption of browsers. But I don’t have any other option, but when I checked the view source option of Update Panel control from Microsoft, or Calendar control code from DayPilot, I am not able to get the actual source. So there are some option available where I can disable users to view the script. Then after some google-ing I got a solution, Embedding a JavaScript File as a Resource in the web control assembly. You can get more information about this in the ASP.Net Ajax official site.

Here is the steps to embed script file.

  1. Right click on the properties of the script file, change the Build Action to EmbeddedResource
  2. Create a new webresource attribute in AssemblyInfo file.
    [Assembly: System.Web.UI.WebResource("MonthView.DragDrop.js", "application/x-javascript")]
    

    You can put this into the same file also, where MonthView is the namespace, DragDrop.js is the script file, and second argument is the resource file type.

  3. Accessing the script file
    You can access the embed file using two ways.

    1. Using ASP:ScriptReference control
      <scripts>
      <asp:ScriptReference Assembly="SampleControl" Name="SampleControl.UpdatePanelAnimation.js" />
      </scripts>
      
    2. Using Page.RegisterScript
      Page.ClientScript.RegisterClientScriptResource(typeof(MonthView), "MonthView.DragDrop.js");
      

    Both will come in the script tags and you can call the functions and methods of the file directly from the page

And the page source you will get some WebResource.axd?some value, as the value of src attribute.

This entry was posted in .Net, .Net 3.0 / 3.5, ASP.Net, Javascript, Visual Studio. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>