C# How to add a script reference at runtime

Most websites are a mix of html/css and a little javascript.
I found myself wanting to dynamicly include or exclude scripts.

In this example I’ve created a master page which contains a scriptmanager, the code below is used in the onload event in the content page.
You can expand the sample code with a case or if statement to determ which script to include.

Sample code:

protected void Page_Load(object sender, EventArgs e)
    ScriptManager _SM =
      ((Master as MyMasterPage).FindControl("ScriptManager1") as ScriptManager);
    ScriptReference _Script = new ScriptReference("~/Scripts/MyScript.js");

For more information see http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx

2 thoughts on “C# How to add a script reference at runtime

  1. What’s wrong with `ScriptManager.GetCurrent(Page)`? If you’re in Page_Load() then you won’t have to worry about `Page` being `null`

    1. Of course you could use an other method of finding the script manager. There is no harm in that.
      The example was mainly to show how to use the script manager to include scripts dynamically and so exclude unnecessary scripts.

      Your method is a good alternative for the line
      ScriptManager _SM =
      ((Master as MyMasterPage).FindControl(“ScriptManager1”) as ScriptManager);

      Thank you for the suggestion.

Comments are closed.