Adrian Grigore
Adrian Grigore

Reputation: 33318

What's the best way to embed constant server-side tags inside javascript code?

I have a bunch of javascript functions which depend on some server-side constants (such as strings from my resources file). While I was developing them I kept the javascript code in the view header, so I could simply used server-side tags inside my javascript code, but now I'd like to move the javascript functions to a separate file.

I can't use a regular js file since that would not be interpreted by the server, making the server tags embedded there useless. I don't want to define variables in the page either since that seems way to awkward and error-prone.

What I've done instead is to create a new aspx file, put the javascript functions there and include that aspx file instead of a regular js file in my master template. It seems a bit unorthodox, but it seems to work fine.

Is there any downside to my approach that I have not taken into account? Or any better (less obscure) method?

Edit Bonus question: Should I use a DOCTYPE inside the included scripts file? After all, the scripts file is included by a script tag already. I tried to mimic regular js files, so I did not specify any DOCTYPE.

Upvotes: 2

Views: 1282

Answers (4)

Wyatt Barnett
Wyatt Barnett

Reputation: 15673

Using a view, with MVC's templating capabilities is a great way to accomplish this. It is easy to maintain, well understood and gets the job done fast. The only real trick is to get it to serve the correct content-type. Doing something like this:

    public ActionResult ConfigurationSettings()
    {
        Response.ContentType = "text/javascript";
        return View(Configuration);
    }

Actually gets you text/html content type. The trick is to make sure you get the last word, add this to your controller:

    protected override void Execute(System.Web.Routing.RequestContext requestContext)
    {
        base.Execute(requestContext);
        requestContext.HttpContext.Response.ContentType = "text/javascript";
    }

And you will get the correct content type; ViewResult seems to force it to go text/html.

Upvotes: 2

swilliams
swilliams

Reputation: 48910

You are using the MVC framework (your question is tagged as such) right? If so, you can create an action that returns a JavaScriptResult that will be executed on page when it loads:

public class JSController : Controller {
    public ActionResult Headers() {
        // create your variables here
        return JavaScript("alert('hi');");
    }
}

And then you can add it to your aspx/master page:

<script src="/JS/Headers" type="text/javascript"></script>

Upvotes: 1

mckamey
mckamey

Reputation: 17539

We use the ScriptDataBlock control from JsonFx to emit variables into the page itself. It acts like a dictionary where the key is the variable name (e.g. "MyNamespace.myVar") and the value is a normal C# value (including whole objects). The control emits appropriate namespace generation and type conversion to native JavaScript types. So in that sense it ends up not being "awkward" or "error prone":

myDataBlock["MyApp.myVar"] = myObject;

If you are doing an external file, then a generic .ashx handler is probably your best bet. It will be lighter than a whole aspx page and gives you pretty raw control over the output. Things you will want to be sure to do are to set the "Content-Type" response header to "text/javascript" (technically incorrect but most common MIME type) and for Internet Explorer which tends to not respect the Content-Type header, also set the "Content-Disposition" header to "inline;MyScriptName.js" so it knows the extension of the content.

Also, if these really are "constants" rather than runtime calculated data, you will want to set the "Expires" header to some future date to encourage the browser to cache the result. That will further reduce your server requests.

Edit: no DocType if you are creating JavaScript. DocType is only for markup.

Upvotes: 1

James Conigliaro
James Conigliaro

Reputation: 3829

The file extension, be it js, aspx, ashx, bla, foo, whatever isn't all that important. If you have server side generated javascript that isn't specific to a page, then creating an ASPX page to render the javascript should be okay.

We'll often use HTTP handlers to generate dynamic javvascript in our systems. We also make sure to set the response headers to text/javascript to let the client browser know that we are sending back javascript.

Upvotes: 3

Related Questions