The same situation occured with me.Yoy Might be using IE.so basically place your javascript code in the end or if you are using jquery then under $(document).ready.
Before Detecting value detect whther it is not null or not an object.
Place your code in try catch block
try{
--;
}
catch(er){
throw ex;
}
Refer the following link
MSDN Microsfot
W3 schools