ASP.net: ClientScript.RegisterClientScriptBlock fires before loading jQuery

An interesting problem here is from some legacy code that I recently looked through. I am trying to add a compression module to a project. It downloads all JS and CSS files, combines them, minimizes and compresses them. I tried a number of solutions, but they all have one fatal problem.

I have javascript that loads through page.ClientScript.RegisterClientScriptBlock in PreRender from MasterPage. The compression module loads as a Script Tag link in MasterPage, but when I launch the page ... the code from PreRender exits from above and gives me the error "$ is undefined", telling me jQuery is not loaded yet.

Also, I can't get past the same issue when it comes to embedded javascript on content pages.

Any ideas as to what causes this? Enlighten me because I have no idea.

+7
source share
4 answers

If you have done this before using RegisterStartupScript (instead of RegisterClientScriptBlock ) and you called $(document).ready(function() from WITHIN that script.

+9
source

If the link of the script tag, which ultimately extends to jquery, is not in the head, but in the body of the page, then $ will be undefined when the script block is executed, unless it is included in the html before opening the <form /> in the rendered html, which I understand where RegisterClientScriptBlock spits out its script (right after this opening tag).

If this is not the case and the unified / mined script is in the head, then I would use a browser debugger like Firebug or IE Dev Tools to make sure the jquery script is included correctly in the unified script.

0
source

I know this answer was late to the party, but try calling ClientScript.RegisterClientScriptBlock in your OnPreRenderComplete (not OnPreRender ). This inserts the code later into the page rendering process.

0
source

All your jQuery code must be written inside the DOM-ready function:

 $(function() { // your code here }); 

no matter where you place it on the page, because the jQuery () function is not available before.

-one
source

All Articles