Why Asp.Net MVC 5 put @Scripts.Render(“~/bundles/jquery”) at the bottom in _Layout.cshtml?

青春壹個敷衍的年華 提交于 2019-12-03 06:53:52

问题


I put <script> blocks which use jQuery in the body of one (and only one) cshtml file which uses the template and they causes error because jQuery is not loaded yet.

What's the point to put the @Scripts.Render("~/bundles/jquery") at the bottom of _Layout.cshtml file?

The bottom of the _Layout.cshtml.

    @RenderBody()
    <hr />
    <footer>
    </footer>
</div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

The following shows the generated source of the cshtml file.

<script>
    $(document).ready(function () { /// $ not defined.
        // .....
    });
</script>

    <hr />
    <footer>
    </footer>
</div>

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>

回答1:


You can use sections :

in your layout :

...
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
@RenderSection("scripts", required: false)
...

in yours cshtml :

@section scripts {
    <script>
        $(document).ready(function () { /// $ not defined.
            // .....
        });
    </script>
}



回答2:


Just enclose it inside section scripts in .cshtml Page as shown.

@section scripts{
  <script>
  $(document).ready(function () { 
    // .....
  });
  </script>
}



回答3:


It's a best practice to load your javascript files after every possible HTML element.

Knowing this, I would place your document ready handler after loading all libs.

 <hr />
    <footer>
    </footer>
</div>

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script>
    $(document).ready(function () { /// $ not defined.
        // .....
    });
</script>



回答4:


If the script is at the top of the page, and there are problems then it may cause the page to stop/take a long time loading. Putting them at the bottom allows the page the render fully before your scripting goes to work.



来源:https://stackoverflow.com/questions/25458717/why-asp-net-mvc-5-put-scripts-render-bundles-jquery-at-the-bottom-in-layo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!