November 30, 2011 9 Comments
Frequently I need to use jQuery in SharePoint but don’t always want to have to edit and publish a revised MasterPage to include the necessary script links that will allow me to access the jQuery libraries. This is where the ScriptLink class comes to our rescue. The ScriptLink class allows us to ‘inject’ resources into our pages without having to update the source HTML. What’s even better is we can deploy ScriptLinks via custom actions so we can use the SharePoint feature framework to affect our changes.
Here’s how I go about creating a feature that when deployed and activated will add the jQuery libraries to my site without changing any pages or MasterPages:
First, I create an new Visual Studio 2010 ‘Empty SharePoint Project’ and add to the project a new ‘Layouts’ mapped folder, to this directory I add all the jQuery (and other) resources I want to use in my site:
Note: I’m creating my own jQuery folder underneath the existing _layouts/inc’ folder. This is because the ‘inc’ folder is one of the few directories underneath the _layouts folder that is automatically configured for caching and anonymous access. You don’t need to create your folder underneath the existing ‘inc’ directory but you should at least be creating your own directory below the _layouts folder.
Next, I create an elements file that includes all the resources I wish to include in my pages. Each resource is added as a CustomAction with the Location attribute set to ‘ScriptLink’ and the ScriptSrc attribute set to the relative path of the resource:
Finally I include the elements file in a feature:
Now once this is deployed to my site and activated, the following script links are automatically included in the rendered HTML of the site:
Now I can use jQuery on my site and I’ve had to alter or switch MasterPage – yay! Obviously deactivating the feature then removes these script links from the rendered HTML.
P.S. One other thing you can do to streamline the solution that contains this feature is to switch off the inclusion of the default assembly that Visual Studio will include with the project. As this solution contains no managed code whatsoever the assembly that gets created for us by default by Visual Studio is totally redundant. To suppress the inclusion of the default assembly in the solution (and therefore the ability to delete the class file from the solution as well), update the solution property ‘Include Assembly In Package’ to False: