10

Is it possible to add javascript reference dynamically from code behind aspx.cs?

Like this:

private void AddScriptReference(string path)
{
   //Add reference to <head></head>
}

Should result in a script reference being added to the head of the page, like this:

<html>
   <head>
      <script type="text/javascript" src="path-to-script.js"></script>
   </head>
</html>

Is this possible?

3 Answers 3

27

Bit late but thought I'd post an answer to this in case anybody else needs it. This solution negates the need for a ScriptManager.

Basically, it's just a case of creating a control and then adding to the head. Here's the code.

LiteralControl javascriptRef = new LiteralControl("<script type='text/javascript' src='path_to_script.js'></script>");

Page.Header.Controls.Add(javascriptRef);
Sign up to request clarification or add additional context in comments.

1 Comment

I appreciate the non-ScriptManager solution. It allows loading script links into the header programatically (e.g. I'm using it in a masterpage to manage the .js weight on site pages).
8

For those who want to know the syntax, here it is:

Master Page:

<asp:ScriptManager ID="ScriptManager" EnablePageMethods="true" runat="server"></asp:ScriptManager>

Code behind:

ScriptReference sr = new ScriptReference("path-to-js.js");
ScriptManager sm = (ScriptManager)this.Master.FindControl("ScriptManager");
sm.Scripts.Add(sr);

Or:

ScriptManager.RegisterClientScriptInclude(this.Page, GetType(), "UniqueID", "path-to-js.js");

But none of these solutions actually add the script to the head of the page..

Comments

7

You can use the ASP.NET Ajax ScriptManager to do so.

Add it to your masterpage, and use ScriptManager.RegisterClientScriptInclude from your codebehind.

1 Comment

Thank you, I should have known this :P

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.