8

I want to change between two pages in html with javascript, but when I change with window.location, the code that is after this sentence continues executing.

So when I do, for example, a call to getElementById() it doesn't recognize the element because the page is still loading.

function myFun(){

    // ...

    window.location = 'page.html';

    // ... wait until page.html is loaded

}

How can I wait until the page is loaded to avoid this problem?

3 Answers 3

14

When you do

window.location = 'page.html';

you replace the page in the browser, the one containing the code of myFun, by a new page. There is no way for the code following this instruction to be executed.

If you want to execute it, and only after that change page (but I don't see the point), then you might do

document.onload = function(){ window.location = 'page.html'; };
Sign up to request clarification or add additional context in comments.

3 Comments

but myFun is placed in a separate .js file.
If it's imported in your html file, it's exactly as if it was directly in the page. Its execution stops when you replace the page.
ok thanks, as you told me that it's impossible I've changed the logic of the program to fix that! :)
3

You can use jQuery document.ready or you can create custom bind like this one. In case you use jQuery.

   $(document).ready(function() {
        window.location = 'page.html';
    });

Comments

2

You can't execute code in your own page after doing window.location = 'page.html';. Your page will be replaced by the new page and the code in the current page will no longer be there.

The only ways to execute some code after page.html is loaded into the current window are as follows:

  1. Load it in an iframe or another window and monitor for when the iframe or window has finished loading. In this way, your current code stays around and is not replaced.
  2. Have some code in page.html that monitors when it finishes loading and trigger your desired action from there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.