Tuesday, December 11, 2012

Add script reference dynamically through code in SharePoint

In this post we will discuss how we can give script reference dynamically using code. You can check my previous posts on JQuery reference in Application pages in SharePoint, Call jQuery to SharePoint page using master page and Deploy jQuery to SharePoint using solution package.

To add script reference dynamically follow below stes:

Step-1:
Open visual Studio 2010, Click on File -> New project. Then from the New Project dialog box, Select Visual C# -> SharePoint -> 2010.
Then from the list of SharePoint 2010 project templates select Empty SharePoint Project. Give a name and make sure .net Framework 3.5 is selected as shown in the figure below:

Step-2:
In the next step Give a local site for debugging and Select Deploy as farm solution and click on Finish as shown in the figure below:

Step-3:
Now Right click on the project -> Add -> New Item

Then from the list of installed templates Select Web Part, Give a name and click on Add as shown in the figure below:

Step-4:
Now open the [web part name].cs file and add the below method:

 protected override void OnPreRender(EventArgs e)
        {
            ScriptLink.Register(this.Page, "jQuery/jquery-min-1.6.js", false);
            base.OnPreRender(e);
        }

Here the jquery-min-1.6.js file should be deployed in the Layouts folder under jQuery directory.