In this example I’m going to show you how to create a feature that will insert the JQuery file directly into SharePoint Library folder and add a script link directly to the page. The advantage of making it a site feature allows you to only have the scripts included if you know jquery is being used on the site. Otherwise you are just loading up the JQuery files on each page for no reason. First you will need to download the latest jquery file from the jquery site. http://jquery.com/ . This example is the Sandbox way of doing it.
- Open visual studio and chose File > New Project
- Select SharePoint > 2010 > Empty SharePoint Project. Name the project JQuerySandbox and click OK.
- In the next dialog, enter a valid URL and select Sandbox
solution. Click Finish.
- Right click the project in the Solution Explorer and select Add > New Item. Select a Module and name it Asset. Click Add.
- Delete the Sample.txt file. Add your Jquery file to the Assets module. Right click Assets select Add > Existing Items. Find the location of your downloaded JQuery file and add it.
- Now open the elements.xml and change the file to look like the following.
<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Name="Assets" Url="SiteAssets"> <File Path="Assets\jquery-1.7.1.min.js" Url="jQuery/jquery-1.7.1.min.js"/> </Module> </Elements>
The Url attribute to the Module element tells SharePoint to deploy this module to the SiteAssets Library.
- Right click your project in the Solution Explorer and select Add > New Item. Select Empty Element and call it ScriptElement.
- Open the Elements.xml file which sites under the ScriptElements item and add the following.
<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <CustomAction ScriptSrc="~SiteCollection/SiteAssets/jQuery/jquery-1.7.1.min.js" Location="ScriptLink" Sequence="100"> </CustomAction> </Elements>
- You might have noticed that when you added the Module a Feature was created. Rename the feature to JQuerySandbox. Double click the JQuery.feature folder, this will allow you to change the title and description. Change the Scope to Site and also add the Asset module and ScriptElement element as items in the feature.
- That’s it. Deploy your solution. On your site you should see it has been deployed and activated.
- To ensure it is currently working, you need to see if the JQuery script is loaded on the page. If using Internet Explorer, press F12 and load up the developers tools. In the Script tab, you can select which script to debug, you should see the jquery file.
- If you deactivate the feature, and then check again, you will find it isn’t showing.
- Lastly, if you deployed this to a Team Site for example, there is a Site Asset library displayed when viewing all Site Content. If you navigate to the folder you should see the jQuery folder and the jquery file which has been deployed by your feature.