SharePoint 2010 - Programmatically Add JavaScript, Meta Tags, and CSS Styles to the Header of Every Page

AID: 6250
  • Status: Published

1920 points

  • Bychapmanjw
  • TypeTutorial
  • Posted on2011-06-16 at 21:52:54
For SharePoint sites, particularly public-facing ones, there are times when adding JavaScript, Meta Tags, CSS Styles or other content to the page <head> section is more practical than modifying master pages.  For instance, you could add the jQuery library to the head of every page.  If adding tags to the page <head> section is the only customization being made side-wide, doing so programmatically instead of modifying and un-ghosting the default master pages will increase the performance of the site.  (Un-ghosting a page means that SharePoint is no longer grabbing the master page from the local hard drive and is instead grabbing it from the Content Database.  This adds another call to the database that isn't necessary unless you have a fully branded master page).

To demonstrate how to accomplish this programmatically using the AdditionalPageHead Content Place Holder, we will make a SharePoint solution in Visual Studio 2010 that adds a custom JavaScript file and a custom CSS file.  This solution could be further extended to dynamically add different content based on configurable settings, however for this demonstration we will keep it simple.

1
Open Visual Studio 2010 on a computer running SharePoint 2010.


2
Select File > New Project.


3
Make sure .NET Framework 3.5 is selected.


4
Under Visual C# > SharePoint >2010, select Empty SharePoint Project.


5
Provide a name and location for the solution, for the demonstration we are using CustomPageHead.


6
Provide the URL to the local SharePoint site used for debugging your solution, for the demonstration we are using http://win7 (the URL of my local SharePoint 2010 site).


7
Select "Deploy as a farm solution." Since we are going to be deploying a user control to the SharePoint 14 HIVE (the local hard drive) it must be a farm solution.


8
Select Finish.


9
Next we will add the custom CSS stylesheet and JavaScript file to the solution.  For demonstration purposes, we will be creating them in Visual Studio, however you may add your own files.
      


            
10
Right-click the solution name (CustomPageHead) in the Solution Explorer.


            
11
Select Add > SharePoint "Layouts" Mapped Folder.  This creates the Layouts folder with a sub-folder that has the same name as the Solution (CustomPageHead).  It is important that custom assets (such as JS and CSS files) are placed in that sub-folder or another sub-folder with a unique name to prevent files from conflicting with built-in SharePoint files or other installed solutions.


            
12
Right-click the CustomPageHead folder under Layouts.


            
13
Select Add > New Item.


            
14
Under Visual C# > Web, select JScript File.


            
15
Provide the new JavaScript file with a name, for this demonstration we are using "custom.js".


            
16
Select Add.


            
17
Right-click the CustomPageHead folder under Layouts.


            
18
Select Add > New Item.


            
19
Under Visual C# > Web, select Style Sheet.


            
20
Provide the new CSS file with a name, for this demonstration we are using "custom.css".


            
21
Select Add.


            
22
To ensure the solution is working when we test it, we will use the custom.css stylesheet to change the background color.  In the custom.css file, replace its contents with:

body
{
		background-color: #777777;
}
                                    
1:
2:
3:
4:

Select allOpen in new window



            
23
Close the custom.js and custom.css files if they are still open.



24
Right click the solution name (CustomPageHead) in the Solution Explorer.


25
Select Add > SharePoint Mapped Folder...


26
Expand the TEMPLATE folder and select CONTROLTEMPLATES.  The designated location for storing user controls in SharePoint is the CONTROLTEMPLATES folder. Unlike the Layouts folder, a sub-folder is not automatically created.


27
Right-click the CONTROLTEMPLATES folder.


28
Select Add > New Folder.


29
Name the folder the same name used for the sub-folder in the Layouts folder (CustomPageHead).


30
Right-click the CustomPageHead sub-folder of CONTROLTEMPLATES.


31
Select Add > New Item.


32
Under Visual C# > SharePoint > 2010, select User Control.


33
Provide the User Control with a file name (CustomPageHead.ascx).


34
Select Add.


35
Expand the CustomPageHead.ascx file in the Solution Explorer.


36
Double-click the CustomPageHead.ascx.cs file to open it.


37
Add a reference to the Microsoft.SharePoint namespace.

using Microsoft.SharePoint;
                                    
1:

Select allOpen in new window



38
In the Page_Load section, add the following to grab the URL of the current site:

string SiteURL = SPContext.Current.Web.Url;
                                    
1:

Select allOpen in new window



39
On the next line, add the following to register the custom.js client script:

this.Page.ClientScript.RegisterClientScriptBlock(
	this.GetType(), "custom.js", SiteURL + "/_layouts/CustomPageHead/custom.js");
                                    
1:
2:

Select allOpen in new window



40
For all other types of <head> section tags (i.e. style sheets and meta tags), put the content of the tag in an override of the OnInit function:

protected override void OnInit(EventArgs e)
{
	Page.Init += delegate(object sender, EventArgs e_Init)
	{
		string SiteURL = SPContext.Current.Web.Url;
                Page.Header.Controls.Add(new LiteralControl(
			"<link rel=\"stylesheet\" type=\"text/css\" href=\""
			+ SiteURL + "/_layouts/CustomPageHead/custom.css\" />"));
                Page.Header.Controls.Add(new LiteralControl(
			"<meta name=\"keywords\" content=\"sharepoint,c-sharp\" />"));
	};
	base.OnInit(e);
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window



41
The complete CustomPageHead.ascx.cs file:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace CustomPageHead.CONTROLTEMPLATES.CustomPageHead
{
    public partial class CustomPageHead : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string SiteURL = SPContext.Current.Web.Url;
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "custom.js", SiteURL + "/_layouts/CustomPageHead/custom.js");
        }
        protected override void OnInit(EventArgs e)
        {
            Page.Init += delegate(object sender, EventArgs e_Init)
            {
                string SiteURL = SPContext.Current.Web.Url;
                Page.Header.Controls.Add(new LiteralControl(
                    "<link rel=\"stylesheet\" type=\"text/css\" href=\""
                    + SiteURL + "/_layouts/CustomPageHead/custom.css\" />"));
                Page.Header.Controls.Add(new LiteralControl(
                    "<meta name=\"keywords\" content=\"sharepoint,c-sharp\" />"));
            };
            base.OnInit(e);
        }
    }
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:

Select allOpen in new window



42
Close any open documents.


43
Right-click the solution name (CustomPageName) in the Solution Explorer.


44
Select Add > New Item.


45
Under Visual C# > SharePoint > 2010, select Empty Element.


46
Give the Empty Element a name (CustomPageHead) and select Add.


47
Replace the contents of the Elements.xml file with the following reference the the CustomPageHead User Control (this tells SharePoint to replace the AdditionalPageHead Content Place Holder with the CustomPageHead User Control):

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Control Id="AdditionalPageHead"
           ControlSrc="~/_controltemplates/CustomPageHead/CustomPageHead.ascx" 
           Sequence="12"/>
</Elements>
                                    
1:
2:
3:
4:
5:
6:

Select allOpen in new window



48
When creating the Empty Element, a Feature file (Feature1.feature) was added automatically.  Double-click the Feature1.feature file to open it.


49
Give the feature a Title and a Description.  These are both displayed on the Site Actions > Site Features page where the feature is activated and deactivated.


50
Leave the Scope set to Web.  A Web in SharePoint is the individual SharePoint site, whereas a Site is a SharePoint Site Collection.


51
Now that the solution is complete, right-click the solution name (CustomPageHead) in the Solution Explorer.


52
Select Deploy.


53
The solution is now deploying to your test SharePoint site.  The results of the deployment will be displayed in the Output window at the bottom of the screen.


54
Once the deployment is complete, visit the test SharePoint site to verify it is working.



Now the solution can be packaged up and deployed to  your other SharePoint farms and sites as necessary.  This solution can be customized to add just about any tags to the <head> sections of each SharePoint page.

Article Source
Asked On
2011-06-16 at 21:52:54ID6250
Tags

sharepoint

,

sharepoint 2010

,

javascript

,

meta

,

css

,

head

Topic

MS SharePoint

Views
1296

Comments

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top MS SharePoint Experts

  1. ACH1LLES

    358,298

    Wizard

    0 points yesterday

    Profile
    Rank: Genius
  2. JamieMcAllister

    189,161

    Guru

    0 points yesterday

    Profile
    Rank: Sage
  3. teylyn

    170,328

    Guru

    900 points yesterday

    Profile
    Rank: Genius
  4. ivan_vagunin

    156,400

    Guru

    0 points yesterday

    Profile
    Rank: Sage
  5. QPR

    123,685

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  6. Tehzar

    100,639

    Master

    0 points yesterday

    Profile
    Rank: Guru
  7. svetaye

    75,681

    Master

    0 points yesterday

    Profile
    Rank: Guru
  8. tedbilly

    71,150

    Master

    0 points yesterday

    Profile
    Rank: Genius
  9. quihong

    52,832

    Master

    0 points yesterday

    Profile
    Rank: Sage
  10. dp_expert

    49,160

    0 points yesterday

    Profile
    Rank: Wizard
  11. colly92002

    41,560

    0 points yesterday

    Profile
    Rank: Master
  12. clayfox

    39,400

    0 points yesterday

    Profile
    Rank: Genius
  13. milindsaraswala

    36,835

    0 points yesterday

    Profile
  14. RainerJ

    31,840

    1,000 points yesterday

    Profile
    Rank: Master
  15. abhitrig

    31,218

    0 points yesterday

    Profile
    Rank: Wizard
  16. dhawalseth

    30,268

    0 points yesterday

    Profile
  17. ImaCircularSaw

    29,438

    0 points yesterday

    Profile
    Rank: Guru
  18. martusha

    25,478

    0 points yesterday

    Profile
  19. zephyr_hex

    21,624

    0 points yesterday

    Profile
    Rank: Genius
  20. FastFngrz

    21,414

    0 points yesterday

    Profile
    Rank: Guru
  21. livanescu

    20,100

    0 points yesterday

    Profile
  22. danshady

    18,870

    0 points yesterday

    Profile
  23. CloudedTurtle

    18,050

    0 points yesterday

    Profile
    Rank: Master
  24. jessc7

    17,102

    0 points yesterday

    Profile
    Rank: Sage
  25. JoeKlimis

    16,318

    0 points yesterday

    Profile
    Rank: Master

Hall Of Fame