Page.RegisterStartupScript Method
-
I am hoping someone can explain to me the rationale behind the Page.RegisterStartupScript method... What does it achieve that simply writing your script to a Literal doesn't? I've never had a reason to use it - if I want to add JavaScript to a page I simply do that. I am no doubt being very silly, but..
-
I am hoping someone can explain to me the rationale behind the Page.RegisterStartupScript method... What does it achieve that simply writing your script to a Literal doesn't? I've never had a reason to use it - if I want to add JavaScript to a page I simply do that. I am no doubt being very silly, but..
It ensures the script is only registered once. For example, if you have a UserControl, you could have multiple instances of it on the page. Writing the script to a literal would output one copy of the script for each instance of the control, whereas
RegisterStartupScript
would (normally) only output one copy. It also ensures that the script is rendered at the bottom of the form, rather than scattered throughout the markup. Not a huge issue, but very satisfying if you have OCD. :)
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
It ensures the script is only registered once. For example, if you have a UserControl, you could have multiple instances of it on the page. Writing the script to a literal would output one copy of the script for each instance of the control, whereas
RegisterStartupScript
would (normally) only output one copy. It also ensures that the script is rendered at the bottom of the form, rather than scattered throughout the markup. Not a huge issue, but very satisfying if you have OCD. :)
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
I am hoping someone can explain to me the rationale behind the Page.RegisterStartupScript method... What does it achieve that simply writing your script to a Literal doesn't? I've never had a reason to use it - if I want to add JavaScript to a page I simply do that. I am no doubt being very silly, but..
In addition to ensuring the script is only written once, if you are writing a user control then you can only control the mark-up inside that control, so it wouldn't be possible to inject a label for js at the bottom of the page. My biggest issue with RegisterStartupScript etc is the name, it should be changed to RegisterStartupScriptPleaseNoteThatYourJSIsNOTBeingExecutedImmediatelyInServerSideCode