asp.net core supplies a layout page region to handle page only scripts and css:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/layout?view=aspnetcore-8.0
note: if using razor pages, you can use css isolation.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello everyone and thanks for the help in advance. I am developing an Asp.Net Core project that utilize layout pages for things like headers and footers. However, many of the pages that use the layout also need specific css and script files. Do I include those in the layout page or what is the best practice for handling this? Any help would be appreciated.
asp.net core supplies a layout page region to handle page only scripts and css:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/layout?view=aspnetcore-8.0
note: if using razor pages, you can use css isolation.
First, your styling and scripts should always be in separate files, not stored directly in the HTML page for security reasons. Put any references to stylesheets and scripts in your layout page if the majority of your pages need it. For example your core styles for the site, commonly needed scripts like jQuery and front end libraries, etc. They all are referenced by the layout page so every page gets them.
For styling/scripts that are only needed on some pages then consider adding them only to the HTML pages that need them. This keeps them from being loaded unless the user actually goes to the page that needs them and therefore speeds up the site. In general you can start with them on the HTML page(s) that need them and "promote" them up to layout if you need them on many other pages. This is sort of like how variables should always start as local variables and then "promote" up to fields or globals if and when they are needed elsewhere.
If you have "sections" (or areas in MVC) of your site where common styling/scripts are needed then consider using nested layouts as well. With a nested layout your site has a core layout and corresponding styles/scripts. You can define a layout that "inherits" from the core layout and adds shared styles/scripts for that section of the site and then each page can include styles/scripts that specific to that page. A common scenario is a site that has the core site being public but the "admin" section having a different set of layouts and files needed for it.