Supposing that:
1. You have a _Layout.cshtml
view like this.
<html>
<body>
@RenderBody()
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
@RenderSection("scripts", required: false)
</html>
2. You have Contacts.cshtml
.
@section Scripts{
<script type="text/javascript" src="~/lib/contacts.js"></script>
}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
3. You have About.cshtml
.
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
On your layout page, if required
is set to false
: @RenderSection("scripts", required: false)
, when the page renders and the user is on the about page, contacts.js
won't render.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
</html>
If required
is set to true
: @RenderSection("scripts", required: true)
, When page renders and user is on the About page, contacts.js
still gets rendered.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
<script type="text/javascript" src="~/lib/contacts.js"></script>
</html>
IN SHORT, when set to true
, whether you need it or not on other pages, it will get rendered anyhow. If set to false
, it will render only when the child page is rendered.