If mathematics teaches us anything, it’s that there are usually multiple solutions for one problem. When you need to add a reference to a JavaScript or CSS file for a .Net web application (such as SharePoint) from the code behind you have many options available to you. Below are two SharePoint specific methods that you can use to reference a JavaScript and CSS file from within a web part (or any other custom code solution.)
Registering Javascript
The first example registers an external JavaScript file. Typically when you reference an external JavaScript file it is cached by the browser so it doesn’t need to be re-downloaded each time the page is loaded. This is good for improving performance, but can be an issue when you update your JavaScript file and find that you are still executing the old JavaScript. Using the below method appends a unique postfix to the JavaScript filename so that a new version is downloaded as needed without having to reset browser files or do other sorts of trickery.
using Microsoft.SharePoint.WebControls;
ScriptLink.Register(this.Page, <JS_FILE_NAME>, true);
Example of output
"text/javascript" language="javascript"
src="/_layouts/1033/MyAppCommon/JS_File_Name.js?97XRFCZSv%2BI8aGRCPfUgTg%3D%3D">
Registering CSS
The second example registers a cascading style sheet. This is useful for when you have a CSS file that contains branding styles that you need to include with a web part but don’t want to include on a master page. This method will handle adding the link to the <head> tag of the page as needed.
using Microsoft.SharePoint.WebControls;
CssRegistration.Register(CSS_FILE_NAME);
Example of output
<link rel="stylesheet" type="text/css" href="/_layouts/MyAppCommon/Css_FileName.css"/>
Conclusion
These are both very simplistic methods that can be utilized on your SharePoint web parts to help you include JavaScript and CSS files. On my current project we have used these quite a bit to pair custom JavaScript and CSS with individual web parts instead of at a higher level where they may not be appropriate. Perhaps you’ll be able to make use of these as well. Until next time, happy SharePoint’ing.
Links
CSSRegistration.Register MSDN page
-Frog Out