Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically changing the script tag source on C# side

How can I dynamically change the <script> src attribute from the Page_Load?

When I say dynamic, I really mean that it's the same page Default.aspx, but each refresh a different js source is referenced. The logic behind which js file to select is of no concern, merely the mechanism to set it.

I tried:

<script id="script1" runat="server" language="javascript" src="a.js" type="text/javascript"></script>

But script1 is not available on the .cs side. I know I can change it on the .aspx side by using the <% %> tags, but I don't want to have my logic embedded like that in my .aspx. There must be a way to do this on the .cs side in Page_Load?

like image 845
user17753 Avatar asked Apr 08 '26 13:04

user17753


2 Answers

On your page load handler you could have something like this

string csurl = null;
string csname = "myscript";
if (condition)
{
    csurl = "~/a.js";
}
else    
{  
    csurl = "~/b.js";
}

if (!Page.ClientScript.IsClientScriptIncludeRegistered(cstype, csname))
{
    Page.ClientScript.RegisterClientScriptInclude(
        this.GetType(), 
        csname, 
        ResolveClientUrl(csurl));
}

or

 string csurl = null;
 if (condition)
 {
     csurl = "a.js";
 }
 else    
 {  
     csurl = "b.js";
 }
 Literal script = new Literal();
 script.Text = string.Format(
     @"<script src=""{0}"" type=""text/javascript""></script>",csurl);
 Page.Header.Controls.Add(script);
like image 83
Claudio Redi Avatar answered Apr 10 '26 01:04

Claudio Redi


There's a few ways to do this. One approach is to make a protected or public method in your codebehind that returns a string, which returns the correct URL to your Javascript based on your criteria. Then, just call that method from your markup, like this:

<script language="javascript" src="<%=GetJavaScriptUrl() %>" type="text/javascript"></script>

This example assumes you call the method in your codebehind GetJavaScriptUrl.

like image 28
wsanville Avatar answered Apr 10 '26 03:04

wsanville



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!