SharePoint: Register java scripts and css in a webpart

There are times when we need to use java script and css in our webparts. Registering the java script and css can be done in different ways. But we need to make sure that if the same webpart is used more than once on a single page then only one instance of the javascript and css are loaded on the page. 
ClientScriptManager can be used to make sure that only one instance of the javascript is loaded on a page. Here is the code snippet.

private const string script = "/_layouts/JQuery/JS/jquery.min.js";
private const key = "scriptKey";
ClientScriptManager cs = Page.ClientScript;
Type csType = this.GetType();
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, scriptKey))
{
    cs.RegisterClientScriptBlock(csType, scriptKey, script );
}


As can be seen RegisterClientScriptBlock method takes the type of the class as parameter, so this will make sure that javascript is loaded only once. But let's consider a case where we have two different webparts on a same page but both refer the same javascript. If we use the above method, then we will have two refernces of javascript loaded as the type of two webparts will be different.
Sharepoint 2010 provides ScriptLink class which can be used to register javascript as follows:
private const string script = "/_layouts/JQuery/JS/jquery.min.js";
ScriptLink.Register(Page, script , false);
This will make sure that javascript is loaded only once even if it is referred in two different webparts.
CSS can be registerd using CssRegistration class.

private const string jqueryCss= "/_layouts/CSS/jquery-ui.css";
CssRegistration.Register(jqueryCss);
profile for Nadeem Yousuf at SharePoint Stack Exchange, Q&A for SharePoint enthusiasts

+