Referencing external JavaScript when building custom SharePoint 2010 ribbon

fix

Sunday, March 21st, 2010

I assume you already tried working with SharePoint 2010 ribbon and you already know the structure of how you can create basic ribbon controls. One of the most commond things that you might be doing when creating your custom ribbon controls is to define JavaScript for the handlers that will be executed upon your conteols being clicked.

One of the most demonstrated examples of how you can define your own Javascript is tihs:

<CommandUIHandlers>
  <CommandUIHandler Command=”Ribbon.MyTab.MyGroup.Button_CMD” CommandAction=”javascript:RibbonButtonHandler();” />
 </CommandUIHandlers>

In here, the highlighted  part if my command. The CommandUIHandler  though doesn’t allow to define external file where all of our scripts will be hosted. This might be puzzling at first and you may think that you need to define all of your Javascript right inside the elements file – which obviously makes it hard to maintain your JS code in afuture.

Well, the good news is that you can reference Javascript external file for your handlers; you will still call your hanbdler function just like in the example from above but here is what you add in your Elements (ribbon definition) file:

<CustomAction Id=”Ribbon.Library.Actions.Scripts”
 Location =”ScriptLink”
 ScriptSrc=”/_layouts/SharePointProject1/RibbonActions.js” />

This will ensure the functions will be accessible from your CommandUIHandler, here is how your hypothetical ribbon definition will look like:

<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”>
 <CustomAction
   Id=”Ribbon.MyTab”
   Title=”Ribbon Sample”
   RegistrationType=”List”
   RegistrationId=”100″
   Location=”CommandUI.Ribbon.ListView”>
<CommandUIExtension>
 <CommandUIDefinitions>…</CommandUIDefinitions>
 <CommandUIHandlers>
  <CommandUIHandler Command=”Ribbon.MyTab.MyGroup.Button_CMD” CommandAction=”javascript:RibbonButtonHandler();” />
 </CommandUIHandlers>
</CommandUIExtension>
</CustomAction>

<CustomAction Id=”Ribbon.Library.Actions.Scripts”
 Location =”ScriptLink”
 ScriptSrc=”/_layouts/SharePointProject1/RibbonActions.js” />
</Elements>

Enjoy!

news

Any information posted on this blog does not reflect views of respective product vendors unless explicitely stated.

featured