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

后端 未结 3 921
野的像风
野的像风 2020-12-11 20:20

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.

相关标签:
3条回答
  • 2020-12-11 20:36

    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.
    0 讨论(0)
  • 2020-12-11 20:42

    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'; };
    
    0 讨论(0)
  • 2020-12-11 20:47

    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';
        });
    
    0 讨论(0)
提交回复
热议问题