I'm trying to figure out the proper Razor syntax to get a JavaScript file for a particular *.cshtml to be in the head tag along with all the other include files that are defined in _Layout.cshtml.
-
7You should also consider putting the js at the bottom of the page instead of in the head section.Mattias Jakobsson– Mattias Jakobsson2010-11-30 08:49:15 +00:00Commented Nov 30, 2010 at 8:49
-
Only issue I found with the sample code is that the @section "JavaScript" need not be enclosed in quotes.Stephen Patten– Stephen Patten2010-11-30 13:44:44 +00:00Commented Nov 30, 2010 at 13:44
-
2One more thing: if this is a JavaScript tag, be careful about the usage, I needed to use the END Tag of the script element to get this to run correctly. <script type="text/javascript" src="@Url.Content("~/Scripts/RDA.js")"></script>;Stephen Patten– Stephen Patten2010-11-30 14:00:22 +00:00Commented Nov 30, 2010 at 14:00
-
@Mattias Jakobsson - Not always. That depends on a specific case.Dimskiy– Dimskiy2011-04-26 17:41:27 +00:00Commented Apr 26, 2011 at 17:41
-
@Dimskiy if you'll allow me to be a word parser and pedant, you should indeed always CONSIDER putting the js at the bottom, whether you actually place it there or not.MrBoJangles– MrBoJangles2013-07-19 19:18:07 +00:00Commented Jul 19, 2013 at 19:18
2 Answers
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
9 Comments
<script> tag - didn't know that (haven't tried named sections with JS yet). now i (and others) will know</body> tag instead of in the head tag. This is so that it wouldn't prevent parallel downloads by the browser. See developer.yahoo.com/performance/rules.htmlTo expand on Stephen Pattens answer, and to completely change my previous version of this answer:
You can add the @RenderSection("JavaScript", required: false) line pretty much anywhere in the file. Meaning, it doesn't have to be in the head or even the footer tag. In the code I'm looking at for work, it's in a div.
Also, you have to put this line into any .cshtml file that's a parent of a partial containing scripts. This allows for nesting partials with scripts, and without having to include all the scripting in the original parent or child. Saying it differently, simply having the RenderSection code in the "layout" or original parent file doesn't automatically cascade to nested partials.
The caveat to this is that your scripts will be scattered throughout the resulting HTML file rendered for the browser. This can lead to debugging difficulties, including accidentally having multiple script methods with the same name or including the same external scripts multiple times.