in the past, script includes were done in the header, so views could just contain javascript snippets anywhere. to speed page performance, script included are moved to after the page html. this means for view javascript to reference scripts (say jquery), it needs to be rendered after the includes, not in the view. the script section in layout allows this, as the script section is rendered after the script includes.
What is Best Practice for where to place Javascript for a View
Coreysan
1,811
Reputation points
In my views, if I need to include Javascript for that specific view only, I will code the page,
then just place the Javascript at the bottom, like this:
<div class="blabla" onclick="bleep()"></div>
<script type="text/javascript">
function bleep() {whatever}
</script>
However, when I ask questions in the forum here, I'll get an answer and I will receive my code back like this:
<div class="blabla" onclick="bleep()"></div>
@section scripts {
<script>
function bleep() {whatever}
</script>
}
For default projects generated by VS, the section is declared in the _Layout.cshtml page at the bottom.
Is this actually a better way to code, rather than how I've been doing it?
I ask because I have several views, and I include javascript that is unique for each view, so I keep it organized and
separated out that way.
Developer technologies | ASP.NET | Other
3,600 questions
Accepted answer
-
Bruce (SqlWork.com) 77,926 Reputation points Volunteer Moderator
2023-01-26T17:15:56.79+00:00