section scripts vs script-tag in asp.net mvc

后端 未结 2 1577
离开以前
离开以前 2021-01-22 16:30

What is the difference of both statements concerning the section Scripts and script-tag? NOT the content inside the scripts that does not interest me.

@section S         


        
相关标签:
2条回答
  • 2021-01-22 17:06

    The first one renders the <script> tag where you have @RenderSection("Scripts") in your layout.

    This is preferred when you don't have to include a script for all pages.

    Also @Scripts.Render will minify and bundle your scripts. Usually this is used at the end of body tag so that Views can get the scripts after the DOM is rendered.

    The second one remains where you use the <script> tag.

    If you use it in Layout, the script is included in all pages (e.g. jQuery).


    Let's take an example

     <!-- HTML in Layout, before Scrip -->
     @RenderBody()
     <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
     @RenderSection("Scripts")
     <!-- HTML after Script -->
    

    Here, if the script make use of jQuery you want to included with section because jQuery is included before section.

    If you include with <script> in your view you will give an error, that jQuery is missing, because is included before jQuery.

    0 讨论(0)
  • 2021-01-22 17:17

    You might want to define sections in you _layout.cshtml file for specific content. It is generally believed that styles belong to <head> and scripts belong before </body>. Your mileage may vary.

    If you just output <script> it will go with all the content and not where you might want it to be. And if script inside view depends on something (jquery) and in your layout you have

    @renderBody()    
    <script src=jquery.js></script>
    @renderSection("scripts",required:false)
    

    then you are screwed (-:

    0 讨论(0)
提交回复
热议问题