What is Best Practice for where to place Javascript for a View

Coreysan 1,811 Reputation points
2023-01-25T18:59:22.02+00:00

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
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,926 Reputation points Volunteer Moderator
    2023-01-26T17:15:56.79+00:00

    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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.