开发者

When to choose Javascript injection from code-behind over external js file

I'm working on a C# web app and I've to handle some javascript code.

I can do it both using javascript injection from my .cs file, which I'm doing now or choose to include my code into an external js file.

I would like to know when you would prefer to choose one way over the other.

According to me, it can be more clear to put code in external .js file and it can ease debugging. Code injection from 开发者_如何学Pythoncode-behind would however keep together all the necessary code for my component.

Can I please have your ideas ?

Thanks.

Pat.


Question #1: Do you need to dynamically generate JS?

Yes - inject from codebehind No - external file

Question #2: Is the usage in a user control that may be used in several projects?

Yes - MAYBE inject, more likely either markup or an external file with a known relative path or a shared absolute path. No - definitely external code.

If the dynamic generation is basically dynamically generating identifiers or numbers in the code, you can inline some ASP tags to get the job done in the markup. In short, dynamic JS should happen when you need it to happen because you can't do it any other way. Making sure dynamic JS works is a two-layer process; make sure the ASP.NET code creates the JS you expect, then make sure the JS you expect actually works as you expect.


You nailed it Pat, look at it the same way that you can choose to have a code behind file or not. ASP.NET is flexible enough to allow you to choose where you want to write your code, but ultimately do whats best FOR YOU.

Generally speaking, best practice is to have separation of code from the UI, separating into more manageable components. Isolating your JS into a separate file affords you other benefits as well. For example, local js files can be pulled into your page load via CompositeScript references in a ClientScriptManager, or even file compression via third party projects found on CodePlex and other websites.

If you can, separate the files, you'll be happy you did in the future.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜