Monday, August 2, 2010

Referencing Javascript Files with SharePoint 2010 Custom Actions using SciptSrc

copy right from: Jan Tielens' Bloggings
If you’re an avid reader of this blog, you are probably aware of the fact that using Javascript plus SharePoint is a very powerful combination. In SharePoint 2007 there were a couple of techniques you could use to make sure your Javascript files would be referenced by SharePoint pages:
  1. Add the Script reference to the Master Page
  2. Use a Delegate Control (e.g. the AdditionalPageHead)
  3. Dynamically through code, e.g. in a Web Part
Although all those techniques work, and will still work in SharePoint 2010, they all have some limitations. The first technique requires you to build a custom Master Page, which may be a little overkill just to get a Javascript file referenced. Additionally, your custom Master Page is not used on Application Pages (unless you use the Superbranding trick). The second is my favorite one in SharePoint 2007, but the requirement is that the Master Page you’re using has the corresponding Delegate Control, and you need to have either a Server Control or Web User Control that generates HTML to reference the script. The third technique is nice if you only want to use the script when the Web Part is on the page, otherwise you’ll have to put the Web Part on every page where you’d like to reference the script.
SharePoint 2010 is adding another very interesting technique to this list; using the ScriptSrc attribute of the CustomAction element in a Feature. Check the following Feature Elements file:
http://schemas.microsoft.com/sharepoint/">
 
      ScriptSrc="
JSDemo/jquery-1.4.2.js"
      Location="ScriptLink"
      Sequence="100"
      >
 
 
The first important thing to notice is that the CustomAction element contains the ScrptSrc attribute that points in this example to the jQuery Javascript library. The jQuery library is added to the /_layouts folder in the SharePoint Root, in a folder called JSDemo (the /_layouts/ prefix is added automatically). By the way, adding files to the /_layouts folder is very easy in a SharePoint project in Visual Studio 2010, using a Mapped Folder.  The second important attribute is the Location; it must be set to ScriptLink so the Javascript file is referenced in the head element of the page. Optionally you can specify a Sequence attribute to determine the in which order the script references will be added (if you have multiple). When Feature is activated, it results in the following HTML:
document.write('

No comments: