简体   繁体   中英

Use page or httphandler to output javascript variables

I have some javascript variables that I want to include in an asp.net page. These are built up in code. I am using these variables in my client side code.

I am wondering is the better approach.

A. Create a httphandler that processes the logic for the variables and handler returns javascript. A reference to handler is included in the master page

B. Master page code behind processes the logic for the variables and returns in the pages markup.

These variables are required on every page.

I am wondering which is the best approach from a performance and best practise point of view.

Reason I like the handler is that it means no javascript is included with markup, total seperation. But the drawback of the handler is that it means an extra http request and may slow down page rendering while the handler is processed.

Opinions?

Interesting question. Typically, I output the variables into a custom namespace (global object) which is basically your option B, but I can't say I have specific reasons for doing so other than having never thought about creating a custom httpHandler!

I am assuming that the generation of the javascript would be handled by a common module and therefore either option could be suitable.

It is unlikely that the additional call to the handler would cause any noticable overhead. We use these for handling images from our database with no issues.

Based on the above, I personally would use the handler, because it is a more elegant solution, albeit a little more complicated.

Handler option seems to be more elegant but it may cost you some trouble beeing cached on server or client side or even at some proxies. I would say go with the simple one.

You could do an HttpModule that writes the javascript directly to the response output. This way you don't have a request to the handler or any markup in the master page.

You can have a block of javascript code that stores these variables in hidden fields market runat=server. You can then pick them up server side on a postback.

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