Adding JavaScript and stylesheets with an AdditionalPageHead delegate control

The AdditionalPageHead control is one of the most commonly used delegate controls by developers to add custom code to the page. Controls registered to the AdditionalPageHead control are added to the <head> element of each page and multiple controls may be added, unlike most other delegate controls that only allow one user control.

In this recipe, we will create an ASCX user control that will add references to a custom stylesheet and custom JavaScript. We will then register the control to be added to the AdditionalPageHead delegate control. Using an AdditionalPageHead delegate control allows us to add our custom stylesheet and custom JavaScript to every SharePoint page, regardless of which master page is being used. This is particularly useful when a custom master page is not required and when managing the master pages for sites on a large scale becomes impractical.

Getting ready

We should have already created our Visual Studio project in the Creating a Visual Studio solution for custom delegate controls recipe of this chapter before starting this recipe.

How to do it...

Follow these steps to create a delegate control to add JavaScript and stylesheet references to each page:

  1. Open the project created in the Creating a Visual Studio solution for custom delegate controls recipe of this chapter in Visual Studio.
  2. Right-click on the folder that was created under the Layouts mapped folder.
  3. Navigate to Add | New Item... as shown in the following screenshot:
    How to do it...
  4. Select Style Sheet by navigating to Visual C# Items | Web:
    How to do it...
  5. Provide the item a name, CustomCSS.css, for example.
  6. Add some content to the stylesheet, at least a CSS comment:
    /* CSS Comment */

    Tip

    As of this writing, there is an unusual behavior between SharePoint and Google Chrome that causes the file to be repeatedly requested by the browser if the file has no content.

  7. Right-click on the folder again and navigate to Add | New Item.
  8. Select JavaScript File by navigating to Visual C# Items | Web as shown in the following screenshot:
    How to do it...
  9. Provide the item a name, CustomJS.js, for example.
  10. Add some content to the JavaScript file, at least a JavaScript comment:
    // JavaScript Comment
  11. Right-click on the folder we created in the CONTROLTEMPLATES mapped folder.
  12. Navigate to Add | New Item.
  13. Select User Control (Farm Solution Only) by navigating to Visual C# Items | Office/SharePoint:
    How to do it...
  14. Provide the item a name, CustomJavaScriptAndStyleSheets.ascx, for example.
  15. Click on Add.
  16. Open the code-behind file for the user control, CustomJavaScriptAndStyleSheets.ascx.cs, for example.
  17. In the CustomJavaScriptAndStyleSheets class, override the CreateChildControls method as follows:
    protected override void CreateChildControls()
    {
    }
  18. In the CreateChildControls method, add a new SPMonitoredScope object:
    using (new SPMonitoredScope("Code6587EN.Ch07.CONTROLTEMPLATES.Code6587EN.Ch07.CustomJavaScriptAndStyleSheets::CreateChildControls"))
    {
    }
  19. Get the URL to our custom JavaScript file with the relative URL of the current site:
    var url = SPContext.Current.Web.ServerRelativeUrl.TrimEnd('/') + "/_layouts/15/Code6587EN.Ch07/CustomJS.js";
  20. Register the JavaScript file with the ClientScriptManager object of the current page:
    this.Page.ClientScript.RegisterClientScriptInclude("CustomJS", url);
  21. Open the ASCX user control, CustomJavaScriptAndStyleSheets.ascx for example.
  22. Add a reference to our custom CSS file using a SharePoint CssRegistration control:
    <SharePoint:CssRegistration ID="customCssRegistration" Name="<% $SPUrl:~Site/_layouts/15/Code6587EN.Ch07/CustomCSS.css %>" runat="server"></SharePoint:CssRegistration>

    Tip

    Stylesheet references may also be added using C# code in the code-behind file. We are adding it in the ASCX file to demonstrate the use of the ASCX user controls.

  23. Right-click on the project name in the Solution Explorer pane.
  24. Navigate to Add | New Item.
  25. Select Empty Element by navigating to Visual C# Items | Office/SharePoint as shown in the following screenshot:
    How to do it...
  26. Provide the item a name, CustomJavaScriptAndStyleSheets, for example.
  27. Click on Add.
  28. In the Elements.xml file of the new element, register our custom control with the AdditionalPageHead control using the following code:
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Control Id="AdditionalPageHead" Sequence="10" ControlSrc="~/_controltemplates/15/Code6587EN.Ch07/CustomJavaScriptAndStyleSheets.ascx">
      </Control>
    </Elements>

    In similar fashion to the Layouts mapped folder, items in a SharePoint 2013 solution within the CONTROLTEMPLATES mapped folder will be located under /_CONTROLTEMPLATES/15/.

  29. Select the new element (not the Elements.xml file within it) in the Solution Explorer pane.
  30. In the Properties pane, click on the ellipsis for the Safe Control Entries option as shown in the following screenshot:
    How to do it...
  31. Add a new safe control entry with the following details:
    • (Name): CustomJavaScriptAndStyleSheets (the name of the user control we created without the .ascx extension)
    • Assembly: $SharePoint.Project.AssemblyFullName$
    • Namespace: Code6587EN.Ch07.CONTROLTEMPLATES.Code6587EN.Ch07 (the full namespace for the user control, without the name of the class itself)
    • Safe: True
    • Safe Against Script: True
    • Type Name: CustomJavaScriptAndStyleSheets (the name of the class for the user control)
    How to do it...
  32. Click on OK.
  33. When the Empty Element item was added, it also added a new feature in the Features folder. Rename the feature to the project name. Each of the elements we add in the recipes for this chapter will automatically be added to this feature:
    How to do it...
  34. Open the feature and provide it an appropriate name, Code6587EN.Ch07 Delegate Controls, for example as shown in the following screenshot:
    How to do it...
  35. Set the scope to Site.
  36. Click on Start from the toolbar to package the solution, deploy it to the local SharePoint server, activate the feature, and attach the debugger to the IIS process:
    How to do it...
  37. Once the SharePoint site is loaded in the web browser (after clicking on Start), view the source of the page to observe the references to our custom stylesheet and JavaScript files.

How it works...

The Elements.xml file of our Empty Element instructs SharePoint to add our referenced user control to the delegate control with the Id of AdditionalPageHead. The sequence provides SharePoint the order in which to add controls referencing the same Id to the page. For delegate controls that accept just one control, only the registered control with the lowest sequence will be added.

An SPMonitoredScope object allows developers to designate portions of code to be monitored for usage statistics in the Unified Logging Service (ULS) logging and the developer dashboard. Using them is not a requirement; however, they do make it easier to identify bottlenecks and other potential issues in custom code. As a matter of best practice, I find it is valuable to use SPMonitoredScopes whenever a block of code affects what is rendered on a page. They do not provide a whole lot of value for backend code that doesn't affect the user interface. The name provided for the scope is a bit arbitrary. You can use whatever you want. However, I find it helpful to use a standard pattern. The pattern used in the examples for this book is Namespace.ClassName::Method. This pattern provides the information required to know exactly where the code is in our project.

Adding our safe control entry to Safe Control Entries of the Empty Element item will add the safe control entry to the SharePoint web application's web.config configuration file. Without this registration, SharePoint will throw an exception indicating the control is not safe when attempting to load it.

Once loaded, our user control will add references to our custom stylesheet and JavaScript files to the page.

Tip

Using the ClientScriptManager object to register our custom JavaScript allows it to be registered with multiple controls, but only added to the page once. It also adds the script references in one group, which is a best practice for web applications in general.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.235.23