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:
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:
and the other option, from code behind, in the Page_Init event handler:
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.