Html 如何等到网页加载了 javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15463003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to wait until a web page is loaded with javascript?
提问by Monica
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?
我怎样才能等到页面加载以避免这个问题?
回答by Denys Séguret
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.
您将浏览器中包含 , 代码的页面替换为myFun
一个新页面。无法执行此指令后面的代码。
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'; };
回答by Emmanuel N
You can use jQuery document.readyor you can create custom bind like this one. In case you use jQuery.
您可以使用 jQuery document.ready或者您可以像这样创建自定义绑定。如果您使用 jQuery。
$(document).ready(function() {
window.location = 'page.html';
});
回答by jfriend00
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.
执行window.location = 'page.html';
. 您的页面将被新页面替换,当前页面中的代码将不再存在。
The only ways to execute some code after page.html
is loaded into the current window are as follows:
page.html
加载到当前窗口后执行某些代码的唯一方法如下:
- 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.
- Have some code in
page.html
that monitors when it finishes loading and trigger your desired action from there.
- 将其加载到 iframe 或其他窗口中并监视 iframe 或窗口何时完成加载。通过这种方式,您当前的代码不会被替换。
page.html
当它完成加载并从那里触发您想要的操作时,在该监控器中有一些代码。