To do this, I use a Delegate Control class, and using that control I target the AdditionalPageHead placeholder. In the server side code within that class, I inject the required client-side code.
First, add an empty class to your SharePoint 2010 project in Visual Studio by selecting Class under the Code Templates in the Add New Item dialog. I named my user control ClientSideDelegateClass (I'll be using C# in this blog entry):
Now we need to specify where to insert the new user control in the SharePoint master page. To do this, simply add another new item - this time, select Empty Element (again, under the SharePoint 2010 Templates in the Add New Item dialog). I called my element ClientSideDelegateCtlElement:
If a feature was automatically created, ensure that it contains ClientSideDelegateCtlElement, and that it is web-scoped. If a feature was not automatically created, then add a new feature and make sure it's configured correctly (you can change the feature name and description as desired):
Next we have to tell SharePoint where to put our newly created web control class (ClientSideDelegateClass). To do this, open up the empty element you created, and insert the following Control element inside the empty Elements tag. However, you will need to change the ControlAssembly and the ControlClass (both lines are highlighted in the below code snip-it) to correspond with your project. And, if you're like me, you'll want an easy way of finding out your assembly's PublicKeyToken...so if you haven't seen this already, check this msdn blog article out.
The last thing you need to do with the element (and I always forget to do this) is register the control as a safe control. You can do this by selecting the element, and adding the control to the Safe Control Entries property collection in the properties window:
NOTE: You may have to modify the Namespace, as I noticed in my environment by default the namespace was not correct.
Ok, now we just have to add the code to our class to inject the client-side code! Open ClientSideDelegateClass.cs, and you will need to add some code (see below):
public class ClientSideDelegateClass : System.Web.UI.WebControls.WebControl
protected override void OnLoad(EventArgs e)
protected override void CreateChildControls()
//inject required client side code here
@" function OnCustomPageLoad()
" _spBodyOnLoadFunctionNames.push('OnCustomPageLoad'); ",
Now deploy the solution to any SharePoint site, and you should see a "Hello World!" messagebox, followed by the background colour changing. And notice that the background color was changed using JQuery, so if the background colour changed, then JQuery has been successfully included as well!
If you have any comments/questions/issues, please feel free to leave a comment on this page and I'll try and respond.