ASP.NET – Including CSS and JS file references

If you’re wondering what is the best way to include CSS and JS file references in ASP.NET pages, here is a quick guide that outlines the available options and shows which approach suits each situation.

First, the most basic approach, can be done from within the head tag, as in the example below:

<head id="Head1" runat="server">
   <title>Title of Page</title>
   <link href="../styles/MyStyles.css" rel="stylesheet" type="text/css" />
   <script type="text/javascript" src="~/scripts/MyJScript.js">
   </script>
</head>

This approach works well for stylesheets &  scripts that are included only in one page, so that you don’t unnecessarily load them in other pages.

It is recommended to use the ResolveUrl function (ex. < %= ResolveUrl(“~/scripts/MyJScript.js”) % >), because the path to these files depends on the path of the page which references them, and using relative paths would be risky.

But if the references are needed in most of the pages, you should place then in the master page. In this case, you will have two options – one similar to the default usage:

<head id="Head1" runat="server">
   <title>Title of Page</title>
   <link href='<%= ResolveUrl(~/styles/MyStyles.css") %>' rel="stylesheet" type="text/css" />
   <script type="text/javascript" src='<%= ResolveUrl("~/scripts/MyJScript.js")' %>">
   </script>
</head>

and the other option, from code behind, in the Page_Init event handler:

Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
   If Not Page.IsPostBack Then
      ' Add JS reference
      Dim myJs As New HtmlGenericControl()
      myJs.TagName = "script"
      myJs.Attributes.Add("type", "text/javascript")
      myJs.Attributes.Add("language", "javascript")
      myJs.Attributes.Add("src", ResolveUrl("~/jscripts/MyJScript.js"))
      Page.Header.Controls.Add(myJs)

      ' Add CSS reference
      Dim myCss As New HtmlGenericControl()
      myCss.TagName = "link"
      myCss.Attributes.Add("type", "text/css")
      myCss.Attributes.Add("rel", "stylesheet")
      myCss.Attributes.Add("href", ResolveUrl("~/styles/MyStyles.css"))
      Page.Header.Controls.Add(myCss)

      linkHome.NavigateUrl = Page.ResolveUrl(PagePaths.Toc)
   End If
End Sub 

Placing the CSS / JavaScript references in the markup is suitable for most of the cases so this should be the default approach.

Including them from code behind is better only in dynamic scenarios – such as when most of the pages use a specific script, but a few pages use a different one. In this case, working from the code-behind makes conditional references easier to implement.

Scroll to Top