Friday, March 25, 2011

SharePoint Custom WebPart Load JavaScript File

To load the JavaScript file (resides in the web site or layouts folder) in a custom web part, add the below set of code statements in the CreateChildControls() method.
using System.Web.UI.HtmlControls;
protected override void CreateChildControls()
{                    
base.CreateChildControls();

string jsFilePath = "/_layouts/MyProject/MyFolder/myJsFile.js";
HtmlGenericControl jsControl = new HtmlGenericControl("script");
jsControl.Attributes.Add("type", "text/javascript");
jsControl.Attributes.Add("src", jsFilePath);
this.Page.Header.Controls.Add(jsControl);
}

No comments:

Post a Comment