Skip to content

Register external JavaScript and Stylesheet

June 30, 2011

Is very common to use external JavaScript and Stylesheet to give a different look&feel to custom webparts. Below are two SharePoint specific methods that you can use to reference a JavaScript and StyleSheet file from within a web part.

Register Stylesheet

There are several ways to add your own CSS to a page, within SharePoint it is recommended that you use the <SharePoint:CssRegistration> control. It’s an ASP.NET control, and looks something like:

<SharePoint:CSSRegistration name="/Style Library/styles.css" After="corev4.css" runat="server" />

How to use this control in code-behind? Well, we can instantiate it or we can use the CssRegistration.Register static method. This method will handle adding the link to the tag of the page as needed. It looks like this:

protected override void CreateChildControls()
{
    CssRegistration.Register("/_layouts/foldername/Style.css");
}

This is quite simple, but this only registers the stylesheet before corev4.css. This is not good if you want to override some styles in corev4.css. To register the stylesheet after corev4.css is something like this:

protected override void OnPreRender(EventArgs e)
{
    CssRegistration css = new CssRegistration();
    css.After = "corev4.css";
    css.Name = "/_layouts/foldername/Style.css";
    this.Controls.Add(css);
}

Register Javascript
To register an external javascript do something like this:

protected override void CreateChildControls()
{
    ScriptLink.Register(this.Page, "/_layouts/foldername/script.js", true);
}

This static method also allows to improve browser performance. Normally the JavaScript file is cached by the browser so it doesn’t need to be re-downloaded each single time the page is loaded. To avoid this the method adds an unique identifier to the end of the JavaScript filename so that a new version is downloaded without having to clear browser cache.

<script type="text/javascript" language="javascript" src="/_layouts/foldername/script.js?F7ERERDCv%2BJD898JNHfPdOI%3D%3D"></script>
Advertisements

From → SharePoint 2010

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: