简体   繁体   English

如何等到网页加载javascript?

[英]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. 我想用javascript在html中的两个页面之间进行更改,但是当我使用window.location更改时,此句之后的代码将继续执行。

So when I do, for example, a call to getElementById() it doesn't recognize the element because the page is still loading. 因此,当我这样做时,例如,调用getElementById()它不会识别该元素,因为页面仍在加载。

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? 我怎么能等到页面加载以避免这个问题?

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. 你用新页面替换浏览器中的页面,包含myFun代码的页面。 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'; };

You can use jQuery document.ready or you can create custom bind like this one . 您可以使用jQuery document.ready ,也可以像这样创建自定义绑定。 In case you use jQuery. 如果你使用jQuery。

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

You can't execute code in your own page after doing window.location = 'page.html'; 执行window.location = 'page.html';后,您无法在自己的页面中执行代码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: 在将page.html加载到当前窗口后执行某些代码的唯一方法如下:

  1. Load it in an iframe or another window and monitor for when the iframe or window has finished loading. 将其加载到iframe或其他窗口中,并监视iframe或窗口何时完成加载。 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. page.html中有一些代码可以监视它何时完成加载并从那里触发所需的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM