views:

120

answers:

6

I need to execute a javascript before the page is start to load? how can i do it? Atfirst my script should execute, after completion of script, if i need i should load the page else i shouln't load it. For example if my script redirect to another page i shouldnot load the current page else i should load it.

+3  A: 

simply write your script in the script tag as a first element in body tag:

-- updated --

for hiding other page elements, use div with full width and height, if you want to show the page, hide the div, that will fix the problem

lakhlaniprashant.blogspot.com
yes I did... But it was execute after the page load...
Ver
for hiding page, use div with full width and height, if you want to show the page, hide the div, that will fix the problem
lakhlaniprashant.blogspot.com
A: 

Script tags are execute as soon as they are encountered. Just put your script tag early, and then use a redirect if your condition is true. Hooking the window.onload event handler is how you get Javascript to trigger on load.

kanaka
yes My script executed as soon as fast... but it loads a current page for 1sec then execute my script...
Ver
+6  A: 

Do it server side ...

The logic you present, seems to fit better at the server side, if you really want to avoid the loading of the page completely..

Gaby
Not sure, but I'd guess this is to redirect to a javascript enabled version of the page/site. As such, it would be browser dependent.
patrick dw
@patrick, looks that way .. My focus was mainly on the **load** part, which is unavoidable... for the *render* there are workarounds, indeed..
Gaby
A: 

Is it possible for you to serve a page initially which contains merely the JavaScript which you need to execute within an HTML document? You can then request the page you want based on the result of the JavaScript.

Mark Chorley
Is this an answer? Add it as a comment
skyfoot
A: 

You could use the jQuery load() method to load a part of a page conditionally, which is not running script before the DOM is ready, but may achieve what you want to do.

izb
A: 

You can't run a script before the page loads (without messing up the document type), but you can put the script early in the page, i.e. in the head section.

You can't stop the page from loading until your script has finished. The page will continue to load in the background, but it will not render until the script has finished.

If you do a redirect in your script, the page will stop loading, but what's already loaded will render while waiting for the new response to arrive.

Guffa