Posted on:
Categories: SharePoint
Description:

​Outside of SharePoint, if we want to include a JavaScript file in a web control, we would normally do something like

if (!Page.ClientScriptManager.IsClientScriptIncludeRegistered(typeof(Page), includeKey))
{
 Page.ClientScriptManager.RegisterClientScriptInclude(typeof(Page), includeKey, scriptUrl)
}

For CSS, I would normally do something like:
bool controlAdded = false;
foreach (Control c in Page.Header.Controls)
{
 if (c.ID == "TestCssLink")
 {
 controlAdded = true;
 }
}

if (!controlAdded)
{
 var css = new System.Web.UI.HtmlControls.HtmlLink
 {
 ID = "TestCssLink",
 Href = cssUrl
 };
 css.Attributes.Add("rel", "stylesheet");
 css.Attributes.Add("type", "text/css");
 Page.Header.Controls.Add(css);
}

Within SharePoint, you could include JavaScript and CSS files in your masterpage or page layouts and call it a day. However if you would like to make the page load leaner and the components more modular, I could still include them when and where I need them by doing the same described above or better, use ScriptLink and CssRegistration as below:
protected override void CreateChildControls()
{
 base.CreateChildControls();
   
 var scriptLink = new ScriptLink
 {
 Name = scriptUrl,
 Language = "javascript",
 Localizable = false
 };
 base.Controls.Add(scriptLink);
   
 var css = new CssRegistration
 {
 Name = cssUrl,
 After = "Themable/corev15.css"
 };
 base.Controls.Add(css);
}