开发者

Difference between Response.Write() and ClientScript.RegisterStartupScript()?

What is the difference between Response.Write() and 开发者_运维百科ClientScript.RegisterStartupScript() Thank you.


The Response.Write method can be used to output code during the rendering phase of the page. The <%= %> server tag is a shortcut for <%Response.Write( )%>.

If you use Response.Write from the code behind, you will write to the page before it has started rendering, so the code will end up outside the html document. Eventhough the browser will execute the code, it doesn't work properly. Having something before the doctype tag will make the browser ignore the doctype and render the page in quirks mode, which usually breaks the layout. Also, as the script runs before anything of the page exists, the code can't access any elements in the page.

The ClientScript.RegisterStartupScript method is the preferred way of adding script dynamically to the page. It will render the script at the end of the form so that it doesn't break the html documnet, and it can access the elements in the form.

Also, you give each script an identity, which means that duplicates are removed. If a user control registers a script, and you use several instances of the user control, the script will only be rendered once in the page.


There is a huge difference.

Basically Response.Write will write to your response stream right now, normally this will put whatever you write at the very top of your page output, even before the tag (unless you call it after the page render event).

When you use RegisterStartupScript it will wait and write your JavaScript to the response stream after the page's controls have rendered (IE, the controls wrote their HTML to the response stream). This means the JavaScript you register will be executed by the browser after the other HTML before it has been loaded into the DOM. This is very similar to the event. Another thing this does is if “registers” the script so if you have more than one control on the page that both need that JavaScript they can check to see if it’s already been registered so it’s only rendered once and both controls use it client side.

Hopefully that makes sense, there are more details then that but I tried to keep it simple.


Response.Write

The Write method writes a specified string to the current HTTP output.

ClientScriptManager.RegisterStartupScript

Registers the startup script with the Page object.


As I think, both these methods are unrelated. Response.Write() can be used to write something on page that is rendered. While ClientScript.RegisterStartupScript() can be used for registering a javascript on page start up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜