Ram Prasad
 

Referencing JS Files using Custom Action element in SharePoint

Nov, 19 2012
 
2 min/s
 
 

JavaScript plays an important role in a SharePoint web application. So, as we customize a SharePoint site, we might across a situation where we need to add our custom JS files to SharePoint pages. There are number of ways to refer a JS file on a SharePoint Page.

Adding a Reference in the Master Page: Add a <script> tag on your master page which points to your custom master page. But in this method, we need to create a custom master page just for referencing the custom JS files.

Using Delegate Control through Feature: We can also add a control in the delegate control section through a feature. But for this we need to create a Server control or a User Control to refer the JS file.

Using ScriptSrc and ScriptBlock of CustomAction: The above two methods are widely used in SharePoint 2007. SharePoint 2010 introduced two new attributes for CustomAction element. Using these attributes we can refer a JS file easily. Below is an sample CustomAction tag which is to be used in the elements.xml file of a feature

  <CustomAction
    ScriptSrc="path of your JS file"
    Location="ScriptLink"
    Sequence="100">
  </CustomAction>

Using this approach we can add the JS files from _layouts directory, a library in a SharePoint site or write the script inline.

Referring JS file from _layouts directory: The below example adds a JS file named 'spdutils.js' from the 1033 folder in _layouts directory

  <CustomAction
    ScriptSrc="1033/spdutils.js"
    Location="ScriptLink"
    Sequence="100">
  </CustomAction>

Referring JS File from a SharePoint Library: The below example adds a JS file from 'Documents' library (Root Site's library) of the SharePoint site

  <CustomAction
    ScriptSrc="~SiteCollection/Documents/spdutils.js"
    Location="ScriptLink"
    Sequence="100">
  </CustomAction>

Adding the JS code directly in the feature: This shows how to add the JS code directly in the CustomAction element using SrciptBlock attribute

  <CustomAction
    Location="ScriptLink"
    ScriptBlock="
	function JSFX_StartEffects()
	{
		JSFX.Fire(200, 100, 100);
	}
	var windowOnload=window.onload||function(){};window.onload=function(){JSFX_StartEffects();};"
    Sequence="103">
  </CustomAction>

With the addition of ScriptSrc and ScriptBlock elements in CustomAction element, we can easily refer JS files on a SharePoint site. And as this has to be done through a feature, it is more manageable and easy to control.