SharePoint Scripting Basics: Master Pages, Caching and Loading Scripts

SharePoint Logo

SharePoint is a functional, feature-rich platform, but there is definitely room for improvement. In this article, I’ll cover some of the basic issues and solutions that you may run into when attempting to extend SharePoint with client-side scripting. It will primarily serve as a reference point for future articles where I would otherwise risk repeating myself.

(Please note that I have access to exactly one, and only one, SharePoint environment: a highly restricted SharePoint 2010 enterprise installation, upgraded from 2007 earlier this year. I have no access to SharePoint Designer or server-side coding of any kind. While much of my advice may be implemented more simply using SP Designer, or changed in SP 2013. While I can’t confirm this, I do welcome additional advice people familiar with these environments may offer.)

Using Master Pages

Microsoft has an excellent Introduction to Master Pages that is well worth reading. In short, Master Pages are just the templates – the frameworks – used to display a site’s pages. In shorter, this means that if you want something done on every page, you need to change the Master Page.

To access the Master Pages available for your site:

  1. Press the “Site Actions” button (upper left corner, usually) and select “Site Settings”.
  2. Find the “Galleries” group and choose “Master Pages”.
  3. Master Pages end with a “.master” extension. The default master pages are generally:
    • SP 2007: default.master
    • SP 2010: v4.master
    • SP 2010 (with Publishing enabled): dayandnight.master
    • SP 2013: seattle.master
  4. Create a backup of your Master Page before you make any changes! You can do this via the Context Menu > “Send To” > “Download a Copy”.

Determining which Master Page is your Master Page can be a little tricky. If publishing is enabled on your site (it’s not on mine), you’ll have a “Master Page” option under “Look and Feel” in Site Settings allowing you to see and change the Master Page. If you have access to SharePoint Designer (I don’t), you’ll be able to see and modify the page there. Otherwise, unfortunately, some trail and error may be needed.

One simple way to do this is to access each available Master Page and add an HTML comment that includes the name of the Master Page. Apply the changes (publish the new pages) and load a page – any page – on your site. You should be able to view the page source discover the elusive identity of your Master Page.

Changing Master Pages

The Master Page template is a complex beast; small changes can have radical impact on your site’s look and feel or may simply break the site completely. The utmost care should be taken when poking at a Master Pages!

Considering this, I prefer to change the Master Page as little as possible. Still, I also like to retain flexibility. To strike a balance, I abstract my changes by adding only pointers to other resources in the Master Page; specifically a single custom script and a single custom style sheet. I can then make changes to those files without further modifying the Master Page.

Lately, I’ve also included a direct reference to my DP_SharePoint library, which allows me to easily leverage its features on any page in my site. I add these lines as a single unit the very end of the HTML HEAD block. The positioning is important for any style changes you may plan on making as you want to load your overrides after the main styles have loaded. Here’s an example of the code I insert:

    <!--- Custom Additions --->
<link rel="stylesheet" type="text/css" href="/sitepath/Style%20Library/Global_CustomStyles.css" />
<script type="text/javascript" src="/sitepath/Style%20Library/Scripts/DP_SharePoint.js"></script>
<script type="text/javascript" src="/sitepath/Style%20Library/Global_CustomScript.js"></script>

A few notes of explanation:

  • Obviously, your site path will differ (and needs to be correct).
  • I use very long, very explicit names for all of my custom files and additions. This is both to improve self-documentation and to reduce the likelihood of name conflicts within the insanely complex SharePoint codebase.
  • The global scripts are stored in the “Style Library” for a very specific reason that we’ll get into below.
  • If, after testing, some pages are not inheriting the changes, it’s likely that your site uses multiple Master Pages. All of them will have to be modified.

It cannot be stressed enough how dangerous modifying Master Pages can be, but it’s also insanely powerful. Code responsibly!

Caching, Scripts and the Style Library

Now that you know how to include new scripts and style sheets on every page of your site, the question remains: where to put them? In SP 2007, the easy answer was: wherever you want. It would work. In SP 2010 the issue became more complex.

Without getting into the dirty details, SP 2010 introduced a new caching mechanism, BLOB Caching, that stores copies of common support files such as images, style sheets and scripts at the web server level. While this greatly speeds up the execution time of complex pages, it also means that any script or style sheets stored by it will be updated when SharePoint wants to, not when you want to.

There is a simple solution, however: SharePoint does not apply BLOB Caching to items in it’s support libraries. I’ve used the “Style Library” (available in publishing sites) and the “Site Assets” library (available in wiki and other sites). So, stuff all of your custom CSS and JavaScript into one of these. To access the Style Library, for example:

  1. Select “All Site Content” from the left menu.
  2. Under “Document Libraries” find and select “Style Library”.

If you don’t find it, look for “Site Assets”. There’s often significant material already in these locations, but you can create whatever folders or naming conventions you like to organize your custom material.

Loading Scripts

Loading JavaScript in a SharePoint page is generally as simple as loading it on any other Web page. Place the script inline or call an external file and the script will run as it’s encountered. However you’ll often want the script you’re loading to modify the page its loading on. The complexity of SharePoint means that knowing when a page is “done” can be tricky.

Happily, SharePoint solves this problem for us by providing a built-in JavaScript function, _spBodyOnLoadFunctionNames. This function has a method, push(), that accepts a function name. The passed function will automatically be run after the page has completed loading.

Here’s a simple example of using this method to run a function named “customOnLoad()”:

<script type="text/javascript">
function customOnLoad() { };
_spBodyOnLoadFunctionNames.push("customOnLoad");
</script>

Of course the function passed must exist and be loaded before the call.

Putting it all Together

What you decided to do with your custom style sheet and JavaScript is completely up to you. Even if you have no need for them immediately, it may be worth it to configure them as blank files. This way, should the need the arise, you’ll only have to edit the custom files.

To give you a sample of what’s possible, I’m going to review my, admittedly simple, personal custom files. My custom style sheet, called Global_CustomStyles.css, contains the following:

                /* Fix Webpart Titles */
.ms-WPTitle {
    font-weight: bold;
    font-size: 125%
    color: #676767
}
                /* Hide "Recent Changes" Left nav area in Wikis */
.s4-recentchanges {
    display: none;
}
                /* Custom Editor Styles */
div.ms-rteElement-custom-breadcrumb {
    -ms-name: "Breadcrumb";
    font-size: 1em;
    font-weight: bold;
}

I won’t go into any great detail on the specifics, but this style sheet does three things that I think are representative of the kind of changes most authors would want to make:

  • The first declaration changes the styling of Web Part titles. I just don’t like the standard styling.
  • The second hides the (I think) ugly and intrusive “Recent Changes” box that appears by default on the left navigation of all wiki pages.
  • Finally, the last declaration adds a custom style declaration (called “Breadcrumb”), to the SharePoint editor.

Similarly, here is my very simple global script file, called Global_CustomScript.js:

function customOnLoad() {
    DP_SharePoint.ReplaceLinks();
};
_spBodyOnLoadFunctionNames.push("customOnLoad");

All this does is create a function, customOnLoad(), that runs DP_SharePoint’s link replacement tool. I use this to include Lotus Notes links (which are normally rejected by the SharePoint editor) and Lync Instant Message presence awareness on my team site pages.

The _spBodyOnLoadFunctionNames function is used, as we learned, to run the function only after the page has completed loading. If you had code that you’d like to run right away, you would simply place it outside the function.

In Conclusion

To review, we’ve learned:

  • How to access and change Master Pages to include common, global style sheet and script files.
  • How to store our custom code in the Style Library to prevent problems with BLOB Caching in SP 2010.
  • How to delay code from running until after the page has finished loading using the built-in _spBodyOnLoadFunctionNames function.

While I also shared some specific examples, I hope that it’s clear I’ve barely scratched the surface. SharePoint is a deep, complex system and there are always going to be quirks that you’ll want to address and changes that you’ll want to make. Using these techniques should take some of the pain out of that work.

2 Comments

Add a Comment

Leave a Reply