7

Is it possible to embed <% ... %> tags in a javascript file and have it render the appropriate server-side code? How can this be done?

1
  • 1
    According to SO, you both answered at the same time. Commented Jun 15, 2011 at 21:31

4 Answers 4

14

The process is actually backwards from what you're thinking.

You create an *.aspx page that renders to a JavaScript file. You can then reference that *.aspx page in your <script> tag:

<script type="text/javascript" src="someJavaScript.aspx"></script>
Sign up to request clarification or add additional context in comments.

1 Comment

What does the .aspx file look like? I almost got this to work, but the second .aspx file doesn't seem to be able to reference anything from the first.
6

Yes, this is possible, but it would not be a JS file, it would be an aspx file with Javascript in it instead of html.

In your page, to refrence it you would do:

<script type="text/javascript" src="myPage.aspx"></script>

Comments

2

I'm going to make some assumptions on what you are trying to accomplish. Most likely you have a javascript file that needs access to some info on the server. Let's say you need some stuff from the session that if it were an aspx page you'd make it look something like

<script type="text/javascript">
var username = '<%= Session["username"] %>';
var account_num = '<%= Session["account_num"] %>';
</script>

obviously this won't work in a .js file since it never goes through the page lifecycle that an aspx page would be processed though. However, you don't need to transform your entire .js file into an .aspx page as some others might be suggesting. There are lots of other ways to expose that data to your js code. I'll list 2.

  1. emit the above <script> in your page response (perhaps using a <asp:ContentPlaceHolder />)
  2. create a webservice (could even be a simple .ashx) that returns the var username = ... or even better returns json

Comments

1

Yes, it's possible by simply making a regular web page that contains Javascript instead.

However, it might not behave like you expect. Javascript files are cached longer than pages. As the browser might not request the file from the server each time, your could would not be executed each time the file is used.

2 Comments

there are lots of ways to make the browser grab it each request
Preventing cache can be a headache. There are headers you can add that work most of the time stackoverflow.com/q/49547/866236 but I've found some browsers still cache files. Adding a get parameter with a timestamp seems to work more reliably: <script type="text/javascript" src="myPage.aspx?t=<%=DateTime.UtcNow.Ticks%>"></script>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.