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
The first approach for calling a function on the page load is the use an onload event inside the HTML <body> tag. As you know, the HTML body contains the entire content of the web page, and when all HTML body loads on the web browser, it will call the function from the JavaScript.
If you load jQuery in the header and all of your other script in a script block at the end of the body, you can be sure that jQuery is loaded before your other code. I try to put everything at the end of the body, with jQuery being the first script loaded.
You can use jQuery and vanilla javascript without having to use noConflict without any problems.
$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ). on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. // A $( document ).
Hide the body with css then show it after the page is loaded:
CSS:
html { visibility:hidden; }
Javascript
$(document).ready(function() { document.getElementsByTagName("html")[0].style.visibility = "visible"; });
The page will go from blank to showing all content when the page is loaded, no flash of content, no watching images load etc.
<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");
Maybe you are using:
$(document).ready(function(){
// Your code here
});
Try this instead:
window.onload = function(){ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With