Question: I am wiring a startup script JavaScript function on Page\_Load to fire like so:

```
ScriptManager.RegisterStartupScript(Me, GetType(Page), "page_init", "page_init();", True)

```

This function calls a couple of different functions to setup the page. One of those functions checks the `document.readyState` and makes sure it's `"complete"`. This deals with images and I want to make sure everything has been fully rendered.

```
if (document.readyState == "complete") {

```

Everything works fine, until I need to write a byte array to the outputstream (using either `Response.BinaryWrite` or `Response.OutputStream.Write()` to give a file to a user. After that, the `document.readyState` is always "interactive", until I navigate off of the page and back. I have even used a `setTimeout(myFunction, 1000);` call if `document.readyState` isn't complete to recursively call the function until it is complete. It never reaches "complete".

I have researched this myself for quite sometime, and cannot figure out this behavior. Any ideas as to how this is happening?

Answer: 
In order for the ReadyState to flip over to Complete, the server side has to terminate the connection. 

If you look at your code you probably aren't calling Response.End AFTER the BinaryWrite or WriteToStream method. This is required in order to flush the response and alert the client that everything has been transferred. 

Note that you can still process data server side after making the Response.End call, you just can't send any more data to the client.

A good example of how to do this properly is page 171 of Mastering ASP.Net with C# by A. Russell Jones ([google preview here](http://books.google.com/books?id=hWzFhJFXadYC&pg=PA171&lpg=PA171&dq=response.binarywrite+terminate+connection&source=bl&ots=dNhh9z-RND&sig=YOUiAnCS7-Xl7Oj5_pW3TYE1Asc&hl=en&ei=GJd3StncF9Xktgf1pdCWCQ&sa=X&oi=book_result&ct=result&resnum=5#v=onepage&q=response.binarywrite%20terminate%20connection&f=false)).

The nut of it is that you should create your stream, read it into the Byte Array, close the stream, then do a BinaryWrite, and finally call Response.End.
Have you tried calling `Response.Close()` instead of or before `Response.End()`? After comparing them in Reflector, it would appear the two are different.