Tuesday, September 10, 2013

Adding Java Script File Reference to Head Tag from WebPart

Scenario: In my recent web part development project, I had to include a custom java script and css file for the UI of the web part. Now, I was writing all the C# code in CreateChildControl so reference to js file comes in the Body tag of the rendered HTML page. Ideally all the references to js and css should render inside the Head tag.

Solution: In CreateChildControl function, use following code:
using System.Web.UI.HtmlControls;

HtmlGenericControl MyJS = new HtmlGenericControl("script");
MyJS.Attributes.Add("type", "text/javascript");
MyJS.Attributes.Add("src", "/_layouts/15/scripts/Mobile_Custom.js");
Page.Header.Controls.Add(MyJS);

HtmlGenericControl MyCSS = new HtmlGenericControl("link");
MyCSS.Attributes.Add("rel", "stylesheet");
MyCSS.Attributes.Add("href", "/_layouts/15/Styles/Mobile_Custom.css");
Page.Header.Controls.Add(MyCSS);