views:

25

answers:

1

Hello, I want to register a jquery-script dynamically on a master page, but it doesn´t work, can anybody help me?

I got the script in a folder Materials/Scripts from the root of my web application, and my master page looks like

public partial class Application : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "jquery",
            VirtualPathUtility.ToAbsolute("~/Materials/Scripts/jquery-1.4.2.min.js"));
    }     
}

But this never works. Using

<script src="../../Materials/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>

works fine.

+1  A: 

When you use the ScriptManager to add a script reference, it adds the SCRIPT tag to the BODY of the HTML page instead of the HEAD section. If you have any jquery code running on $(document).ready() it won't work, because jQuery is not loaded yet.

View the HTML generated by the aspx page and see where your jQuery code is and where the <script> tag referencing jQuery is.

One way to get around this is to add your javascript at the bottom of the document instead of the HEAD.

Another option, if you still want to keep your code in the HEAD, is to use window.onload instead of $(document).ready() for example:

window.onload = function() {
 ... your jquery code here
}
Jose Basilio
Ups, the dynamic registering of the script actually works, but NOT on the Master-Page. I get a JS error if I try to execute a script there. The script is in the body of the page.
Jan-Frederik Carl