A Bogus
A Bogus

Reputation: 3930

JavaScript and jQuery only needed for certain pages

I have a C#, MVC website, I want to have all JavaScript/jQuery needed for the site to be contained in one file, but some of the JavaScript/jQuery is only needed on certain pages.

Example, Currently in the JavaScript file, I have code like the following -

$(document).ready(function () {

    $('#myId').click(function () {
        doCoolStuff();
    });

});

The above statement is executed on every page, but it is only needed on one. What is the best way to have JavaScript/jQuery run only on the page (or pages) that need it?

Upvotes: 2

Views: 149

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

You can use Sections to include items when they are necessary, and make it unrequired (but included when it's present).

_Layout.cshtml

@* ... *@
@RenderSection("Scripts", required: false)
@* ... *@

SomeView.cshtml

@* ... *@
@section Scripts
{
    @* direct inclusion *@
    <script>
        $(function(){
            // your code here
        });
    </script>

    @* or file reference *@
    <script src="@Url.Content("~/Content/alternate.script.js")"></script>
}
@* ... *@

Upvotes: 3

Related Questions