页面加载完成后如何执行 JavaScript 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3261969/
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 can I execute a JavaScript function after Page Load is completed?
提问by Nithesh Narayanan
How can I execute a JavaScript function after Page Load is completed?
页面加载完成后如何执行 JavaScript 函数?
回答by Sarfraz
Use the onloadevent like this:
onload像这样使用事件:
window.onload = function(){
// your code here.......
};
回答by David W. Keith
To get your onload handler to work cleanly in all browsers:
要让您的 onload 处理程序在所有浏览器中都能正常工作:
if (addEventListener in document) { // use W3C standard method
document.addEventListener('load', yourFunction, false);
} else { // fall back to traditional method
document.onload = yourFunction;
}
See http://www.quirksmode.org/js/events_advanced.htmlfor more detail
有关更多详细信息,请参阅http://www.quirksmode.org/js/events_advanced.html
回答by Paul D. Waite
Most JavaScript frameworks (e.g. jQuery, Prototype) encapsulate similar functionality to this.
大多数 JavaScript 框架(例如jQuery、Prototype)都封装了与此类似的功能。
For example, in jQuery, passing a function of your own to the core jQuery function $()results in your function being called when the page's DOM is loaded. See http://api.jquery.com/jQuery/#jQuery3.
例如,在 jQuery 中,将您自己的函数传递给核心 jQuery 函数会$()导致在加载页面的 DOM 时调用您的函数。请参阅http://api.jquery.com/jQuery/#jQuery3。
This occurs before the onloadevent fires, as onloadwaits for all external files like images to be downloaded. Your JavaScript probably only needs the DOM to be ready; if so, this approach is preferable to waiting for onload.
这发生在onload事件触发之前,因为onload等待所有外部文件(如图像)被下载。您的 JavaScript 可能只需要准备好 DOM;如果是这样,这种方法比等待更可取onload。
回答by Newbie
Event.observe(window, "onload", yourFunction);
Event.observe(window, "onload", yourFunction);

