21 September 2011

SharePoint: Programmatically add JS/CSS to pages

John Chapman has a great article on creating a feature for your SharePoint installation that adds JavaScript and CSS files to all pages without touching the site's master page. The good folks on SharePoint.StackExchange.com helped me implement it and also modify the code to better utilize SharePoint's native control libraries.

First, follow the code provided by John Chapman. Then modify the CustomPageHead.ascx.cs to take advantage of the built-in SharePoint controls:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CustomPageHead.CONTROLTEMPLATES.CustomPageHead
{
public partial class CustomPageHead : UserControl
{
protected override void CreateChildControls()
{
base.CreateChildControls();

this.Controls.Add(new ScriptLink()
{
Name = "/_layouts/CustomPageHead/jquery-1.6.2.min.js",
Language = "javascript",
Localizable = false
});

this.Controls.AddAt(0,new ScriptLink()
{
Name = "/_layouts/CustomPageHead/some-custom-code.js",
Language = "javascript",
Localizable = false
});

this.Controls.AddAt(1,new CssRegistration()
{
Name = "/_layouts/CustomPageHead/some-stylesheet.css"
});
}
}
}
Note that using the native controls, you don't have to worry about paths to where the files will be; SharePoint will place these items in the following location on your server:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\CustomPageHead
Also, the advantage of using the this.Controls.AddAt() method is that you can specify where in the object hierarchy to add the specified object.

In addition, the solution can be generated into a *.WSP by selecting "Package" from Visual Studio's Build menu. The file can then be copied from the bin/Release folder and run on the command line to install the feature.

Special thanks goes to omlin and James Love for their help.

No comments: