1

I have 3 views in my MVC5 App. Say A,B,C and 3 javascript files A.js, B.js C.js

When appropriate view is loaded, I want appropriate javascript files to get loaded. I do not want all files to get loaded at the start up.

How do I achieve that?

3
  • 1
    add the script include in the specific view Commented Aug 6, 2014 at 5:35
  • 1
    in a view @scripts { <script src="a.js"></script> } and etc. Commented Aug 6, 2014 at 5:38
  • 1
    If you will ever have multiple JS files per view, create new script bundles in the BundleConfig.cs file (named after the view/purpose) and reference those, one in each view. That way you will get the most efficient caching. I generally recommend using bundles, even for single files, to keep the maintenance in once place. Commented Aug 6, 2014 at 8:11

1 Answer 1

5

In ViewA, add the following

@scripts {
    <script src="A.js"></script>
}

In ViewB, add the following

@scripts {
    <script src="B.js"></script>
}

and so on...

If you are using a _Layout.cshtml, make sure you have the proper RenderSection:

@RenderSection("scripts", required: false)

then in the views itself do this:

@section scripts {
    <script src="B.js"></script>
}
Sign up to request clarification or add additional context in comments.

1 Comment

where should you put the A.js file? inside the wwwroot?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.