Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until a web page is loaded with javascript?

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?

like image 561
Monica Avatar asked Dec 04 '22 12:12

Monica


1 Answers

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'; };
like image 194
Denys Séguret Avatar answered Jan 07 '23 18:01

Denys Séguret