The best strategy for including JavaScript in partial parts of MVC. Please advise

I'm looking for some advice, please. I am developing a large enough ASP.NET MVC 3 application.

There are hundreds of particulars in the system, so I can break the application into composite pieces. Many partial files contain various jQuery or direct javascript script blocks.

The problem is that every time a partial part is included in the main page, the script block will obviously be included every time, which is not the desired effect, clearly.

I could put scripts on the main page, but often there are many long detailed scripts, and I don't want to clutter up the page if scripts are not needed. (Several times partial may appear in ZERO or more times).

What is the recommended approach to enable the script IF block and ONLY if the partial part is included in the page AND also included it only once?

Thanks,

Simon.

+4
source share
2 answers

I had a situation like this; large MVC3 application with numerous partial (containing their own scripts). The approach I took was to name the spaces of objects. You can call your partial view scripts and then check when partial loads detect if a namespace exists or if it needs to be created:

if(window.AppName.Module == undefined){ //Do initialization window.AppName.Module = {}; //Call init or whatever here } //Else continue on... 
+1
source

You can add this module to your particles.

 (function (appname, undefined){ // use appName object here .. })(window.AppName = window.AppName || {}); 
+1
source

Source: https://habr.com/ru/post/1446563/


All Articles