In MVC5 Why is placing @Scripts.Render below @RenderBody standard in _Layout.cshtml
@Scripts.Render
should be at the bottom of the page. Otherwise, you will have risks of accessing page elements which haven't been loaded at the time the scripts run.
EDIT:
If you want to include your custom scripts files, there are two ways of doing that:
1. In the BundleConfig.cs, add a new bundle for your scripts
*bundles.Add(new ScriptBundle("~/bundles/UserScripts").Include("~/Scripts/MyScripts.js"));*
Next, in the _Layout.cshtml, render the script bundle after jQuery bundle:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@* Render the custom bundles *@
@Scripts.Render("~/bundles/UserScripts")
2. Or add a new script section to your Index.cshtml file:
@section scripts {
<script src="~/Scripts/MyScripts.js"></script>**
}
Michael Witt
I have been developing software since 1985.: DEC Vax - C Programming - Ingres Database Unix (AIX/Ultrix/SCO) - 4GL programming - Informix Database Windows NT - C++ programming - Oracle Database Windows 2003 - Visual Basic and ASP programming - Oracle Database Windows 2008 - C# Winforms and ASP.NET programming, Silverlight and WCF - SQL Server DB Windows 2008R2 - ASP.NET MVC, WCF - SQL Server DB Front End - AngularJS, Bootstrap, TypeScript, Angular Quite a ride...
Updated on July 09, 2022Comments
-
Michael Witt almost 2 years
When I generate a MVC5 app, the
_Layout.cshtml
has the@Scripts.Render
at the end of the file after the@RenderBody()
. If I add a.js
into myindex.cshtml
that uses jquery, I get the dreaded "$
is undefined" error.The only way I know to fix this is to move the
@Scripts.Render
to the<head>
section.What is the correct approach?
Thanks in advance!
-
Michael Witt about 10 yearsRight I was pretty sure that was so. But the javascript that I put at the bottom of my index.cshtml: <script src="@Url.Content("~/Scripts/bpindex.js")" type="text/javascript"></script> Since this needs to come before the jquery js file, how does this happen if the js file I'm adding is before jquery include?
-
Michael Witt about 10 yearsThanks @ToanNguyen, your answer does work just fine.