Hi I am creating some web parts in SharePoint 2010 non sandboxed solution. I want to include some JavaScript files and CSS on each page of my site. But I don't want to include my files on each web part or in master page as master page may be changed. Is there any way so that I could dynamically load js/css files which are relevant to a specific page only? Kindly suggest. Thanks
1 Answer
Give that you are not using a sandboxed solution, you can use a Delegate Control, specifically the AdditionalPageHeadDelegate:
You nee to create an ASP.Net Control (ascx file) where you will add the script and css references to the markup
Add a feature, and scope it to Web Application
Add an empty Elements.xml file to the feature ("Empty element" in the Add.. dialog)
Add a the following to your Elements.xml file
<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Control Id="AdditionalPageHead" Sequence="90" ControlSrc="~/_CONTROLTEMPLATES/Microsoft.PFE.DSE.Samples/jQueryControl.ascx" /> </Elements>
...changing the
ControlrSrc
to match the relativt path to your created ascx file
Complete guide, and loose source of the above: http://blogs.msdn.com/b/kaevans/archive/2011/04/06/adding-jquery-to-every-page-in-sharepoint-with-delegate-controls.aspx
Otherwise, look in the a CustomAction: http://weblogs.asp.net/jan/scriptsrc-referencing-javascript-files-with-sharepoint-2010-custom-actions
-
You don't add a webpart to each and every webpart.. you add it as a separate element in a separate feature, and activate it once at the web application level as I write above Commented Jul 2, 2014 at 6:39
-
2You can also use some cool code behind in the ascx control code to target differents scripts and css to different types of sites and pages etc. Commented Jul 2, 2014 at 6:40