简体   繁体   中英

Best placement for javascript in Asp.net MVC app that heavily uses partial views

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM