views:

92

answers:

4

I have a script that I want to run before the page start to load. The script checks the value of a variable and depending on the value redirect the user to a new page.

I can successfully check the variable and redirect if needed but the page still loads and display empty page but then quickly redirects to the other page. I don't want that empty page to be displayed on the page at all before the redirect.

Thank you, Ver

+1  A: 

Maybe you are using:

$(document).ready(function(){
   // Your code here
 });

Try this instead:

window.onload = function(){  }
Trufa
Yes I am using $(document).ready(function(){ // Your code here }); this function only.Is There any possible to do that in javascript
Ver
Code within `$(document).ready()` is run after your page is read, but before additional assets (e.g. images) are finished downloading. You *will* see something on the screen before scripts wrapped in `$(document).ready()` are run.
Blackcoat
A: 

If you don't want anything to display before the redirect, then you will need to use some server side scripting to accomplish the task before the page is served. The page has already begun loading by the time your Javascript is executed on the client side.

If Javascript is your only option, your best best is to make your script the first .js file included in the <head> of your document.

Instead of Javascript, I recommend setting up your redirect logic in your Apache or nginx server configuration.

Blackcoat
+1  A: 
<head>
  <script>
    if(condition){
      window.location = "http://yournewlocation.com";
    }
  </script>
</head>
<body>
  ...
</body>

This will force the checking of condition and the change in url location before the page renders anything. It is worth noting that you will specifically want to do this before the call to the jQuery library so you can avoid all that library loading. Some might also argue that this would be better placed in a wrapper method and called so here is that method:

function redirectHandler(condition, url){
  if(condition){
    window.location = url;
  }else{
    return false;
  }
}

That would allow you to check multiple conditions and redirect to different locations based on it:

if(redirectHandler(nologgedin, "/login.php")||redirectHandler(adminuser, "/admin.php"));

or if you only need it to run once and only once, but you like having nothing in the global namespace:

(function(condition, url){
  if(condition)window.location=url;
})(!loggedin, "/login.asp");
Gabriel
A: 

Don't use $(document).ready() just put the script directly in the head section of the page. Pages are processed top to bottom so things at the top are processed first.

liammclennan