Decrease Font Size
Increase Font Size
   BLOG

ASP ASP.NET load JavaScript dynamically with no duplicate

Using JavaScript Along with ASP.NET |

Using JavaScript Along with ASP.NET 2.0 |

How to load a Javascript file in Asp.Net 2.0? |

Dynamically add JavaScript at pageload |

ASP.NET load JavaScript dynamically with no duplicate

 

I have an ASP.NET WebUserControl that requires a JavaScript to function correctly. My goal is to not include the JavaScript in any of my Page or Masterpage whenever I consume the WebUserControl. All I want to do is just drag and drop one or more of the WebUserControl on to my page and I'll be good to go. I can solve this maze by loading the JavaScript in my WebUserControl dynamically. But it will load duplicates JavaScript on my page if I have more than one of the identical WebUserControl. If you happen to come across into this kind of situation, here is the solution on how to prevent loading duplicate JavaScript on your page. It works for me, comments are welcome.

Use this code in the WebUserControl

protected void Page_Load(object sender, EventArgs e)
{
   LoadJScript();
}

//load the javascript
    internal void LoadJScript()
    {
        ClientScriptManager script = Page.ClientScript;
        //prevent duplicate script
        if (!script.IsStartupScriptRegistered(this.GetType(), "MultipleSelectionDDLJS"))
        {
            script.RegisterStartupScript(this.GetType(), "MultipleSelectionDDLJS",
            "<script type='text/javascript' src='JScript.js'></script>");
        }
    }

Reference

Comments (5) -

  • contador de visitas

    9/22/2009 6:42:57 AM |

    Great blog.It is really informative article. Thank you for sharing your experience and teaching us

  • Free Blackberry Applications

    9/23/2009 4:45:01 PM |

    Thanks for posting this useful guide..

  • waggi

    11/4/2009 5:26:13 AM |

    Great post.

  • Paul

    1/6/2010 12:56:08 PM |

    Hi,

    In my Page_Load I have similar code. I tried even this one.
    Since I have many page loads, the parameter evaluated
    with if(!script.IsStartupScriptRegistered()) doesn't perist between
    the page loads. Still, the JavaScript code loads every time correctly.
    When I use a static variable (in a static class), it keeps the register
    state, and the script is registered just once. But this is not a very
    elegant solution. Please provide me with some advice how to solve
    this IsStartupScriptRegistered() behavior.

    Thanks,

       Paul

  • football shirts

    1/15/2010 10:58:01 PM |

    Good post, but have you thought about ASP ASP.NET load JavaScript dynamically with no duplicate before?

Pingbacks and trackbacks (2)+

Add comment

Loading