Sjoerd
Sjoerd

Reputation: 75619

Add ScriptReference to dynamic script

I want to make texts from a database available in Javascript. I have made Texts.aspx which outputs Javascript code, and I want to include it. The includes have to be done in the right order, because Texts.aspx uses functions from other Javascript files. I tried adding a ScriptReference to this aspx file, but this breaks things. The following code gives a 404 error on ScriptResource.axd.

 <asp:ScriptManager runat="server" EnableScriptGlobalization="true">
     <CompositeScript>
         <Scripts>
             <asp:ScriptReference Path="~/Scripts/textFunctions.js" />
             <asp:ScriptReference Path="~/Scripts/Texts.aspx" />
             <asp:ScriptReference Path="~/Scripts/useTexts.js" />
        </Scripts>
    </CompositeScript>
</asp:ScriptManager>

How do include a dynamically generated Javascript file?

Upvotes: 1

Views: 2129

Answers (2)

Sjoerd
Sjoerd

Reputation: 75619

No, this is not possible. A ScriptReference makes a reference to a set of script which are then read from disk, so it is not possible to make a ScriptReference to a HTTP location.

Upvotes: 0

Damian
Damian

Reputation: 511

Please use IHttpHandler instead of standard aspx page as it is what you are really look for. If you have to use aspx file be sure that you are returning only javascript content there and also that you set content type as it should be for javascripts.

For example:

public class Texts : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/javascript";
        context.Response.Write("var texts = { Some: 'some text here' }");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Than in master or aspx

<asp:ScriptManager runat="server" ID="sm">
    <Scripts>
        <asp:ScriptReference Path="/Scripts/jquery-1.4.1.js" />
        <asp:ScriptReference Path="/texts.ashx" />
    </Scripts>
</asp:ScriptManager>

and finally you can confirm it works (also you will see in firebug that you ashx file is correctly recognized as javascript)

<script type="text/javascript" language="javascript">
    alert(texts.Some);
</script>

Upvotes: 1

Related Questions