Blogging on programming and life in general.

Reference Custom CSS and JavaScript files in SharePoint 2010

Posted in: Sharepoint

I have been building a custom .NET web part page to use in my SharePoint intranet. The .NET page has quite a lot of custom HTML and jQuery design elements, so using CSS and JavaScript files were essential.

As you know, when we want to use elements from our CSS and JavaScript files we normally add the following lines of HTML at the top of our page:

<!-- CSS -->
<link type="text/css" rel="stylesheet" href="site.css" />

<!-- JavaScript -->
<script src="jQuery.js" type="text/javascript" />

If you added those lines of code in a custom SharePoint page, you’ll find that the page will ignore them. Thankfully, SharePoint has given us some controls to add these references.

At this point its worth stating that I stored all my required JavaScript and CSS files within the “Style Library” directory situated in the root of any SharePoint 2010 intranet. In order to get these files I used controls called”CssRegistration” and “ScriptLink”:

<!-- CSS -->
<SharePoint:CssRegistration ID="CssRegistration1" Name="/Style Library/Home/CSS/jcarousel.css" runat="server" After="corev4.css" />

<!-- JavaScript -->
<SharePoint:ScriptLink ID="ScriptLink1" Name="~sitecollection/Style Library/Home/JS/jquery-1.4.4.min.js" runat="server" />

If you have stored your CSS and JavaScript within the physical file directory situated in the 14 hive folder, you will need to modify the above example to the following:

<!-- CSS -->
<SharePoint:CSSRegistration Name="<% $SPUrl:~SiteCollection/Style Library/Core Styles/jcarousel.css%>" runat="server"/>

<!-- JavaScript -->
<SharePoint:ScriptLink ID="ScriptLink1" Name="<% $SPUrl:~SiteCollection/Style Library/Core Styles/jquery.js%>" runat="server" />

The only difference between this example and our earlier example is that when we have just added “SPUrl” to get files relative to the current site collection.

blog comments powered by Disqus