简体   繁体   中英

What is the best way to programmatically run javascript when an ASP.net page loads?

In my global.asax file for my ASP.net project, I am checking for certain conditions. When those conditions are met, I want to automatically execute javascript code when the page runs.

This is my code:

if condition Then
Response.Write(" < script type=""text/javascript"" > ")
Response.Write(" // Javascript code to do stuff ")
Response.Write(" < /script > ")
End If

While this appears to work to execute the Javascript code, I don't think it's a best practice because this code will preceed all of the HTML of the page that gets loaded.

What is the best way of programmatically tacking on some extra Javascript code to be run when my page loads?

Thanks for the answer. 感谢您的回答。 Too bad this solution doesn't work from within global.asax . Is there no way to make this happen site-wide? It seems like global.asax would be the logical place to put code that runs with every page... Response.Write works fine in global.asax .

To correctly manage the placement of scripts from server controls or pages, you should use ClientScriptManager.RegisterStartupScript()

You can also use the equivalent method in the ScriptManager if you are using ajax controls in your site: ScriptManager.RegisterStartupScript

These methods take care of outputting your script in the appropriate locations to be run when the document is finished loading. The links posted have some good examples to work from.

Note that you won't be able to use these methods directly from global.asax, as it has no reference to the current page. Global.asax is for hooking events to the HttpApplication pipeline, and is decoupled from the actual HttpHandler such as your Page object. To keep the separation of UI, you'd be better off to do the check in your master page or in some base page class, and output the script from there.

back in the days of asp.net ajax 1.0 we had something called Sys.WebForms.PageRequestManager in the ajax client libraries. Haven't worked with asp.net 3.5 and asp.net ajax, but I am sure it is simply enough to add the asp.net ajax javascript file into your page and you'll be able to make use of it. Check out for an event called pageLoaded event.

ps: this event will fire every time there is a sync or async postback

If you want to do it on every page, put it on your masterpage if you have one.

If not, you can create a base Page class, that inherits from System.Web.UI.Page and extend it to check your conditions & render javascript.

Then in the codebehind of each page, inherit your base Page Class instead of System.Web.UI.Page

public partial class Orders : MyCode.BasePage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM