3

What is the best place for javascript that is specific to a partial view? For example, if I have a partial view (loaded via ajax call) with some divs and I want to turn those divs into an accordian, would it be better put the $("#section").accordion() in script tags inside of the partial view, or in a .js file in the function that retrieves that partial view and inserts it into the DOM?

Obviously, common methods I will be keeping in a .js file, however I am more talking about javascript very specific to the partial view itself.

Most things I find on the net seem to say to put all javascript into a separate .js but nothing addresses the idea of partial views.

1 Answer 1

3

You can think of partial views as just more html in your web page, if that will help. The browser makes no distinction between html within the partial view, and the rest of the html surrounding it.

By that logic, the best place to put Javascript (including references to outside scripts) in a web page (whether it contains html that is part of a partial view or not) is in its canonical location at the bottom of the page, although there are exceptions.

If it will help the organization of your code, feel free to put the Javascript code that is specific to the partial view html in its own script file, and reference it in the web page at the bottom, with the rest of the script. Doing this will make no difference to the browser.

Sign up to request clarification or add additional context in comments.

1 Comment

So, if he rendered the same view twice, there would be tags with the same ID, and the javascript would execute on both of them?

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.