Javascript 页面加载完成后执行函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11936816/
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
execute function after complete page load
提问by Neeraj Kumar
I am using following code to execute some statements after page load.
我正在使用以下代码在页面加载后执行一些语句。
<script type="text/javascript">
window.onload = function () {
newInvite();
document.ag.src="b.jpg";
}
</script>
But this code does not work properly. The function is called even if some images or elements are loading. What I want is to call the function the the page is loaded completely.
但是这段代码不能正常工作。即使正在加载某些图像或元素,也会调用该函数。我想要的是调用页面完全加载的函数。
回答by Shreedhar
this may work for you :
这可能对你有用:
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
or if your comfort with jquery,
或者如果您对 jquery 感到满意,
$(document).ready(function(){
// your code
});
$(document).ready()
fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).
$(document).ready()
在 DOMContentLoaded 上触发,但此事件在浏览器中并未一致触发。这就是为什么 jQuery 很可能会实施一些繁重的解决方法来支持所有浏览器。这将使使用普通 Javascript 来“精确”模拟行为变得非常困难(但当然并非不可能)。
as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout
function, before firing the function like below :
正如 Jeffrey Sweeney 和 J Torres 所建议的那样,我认为setTimeout
在触发如下功能之前最好有一个功能:
setTimeout(function(){
//your code here
}, 3000);
回答by T.Todua
JavaScript
JavaScript
document.addEventListener('readystatechange', event => {
// When HTML/DOM elements are ready:
if (event.target.readyState === "interactive") { //does same as: ..addEventListener("DOMContentLoaded"..
alert("hi 1");
}
// When window loaded ( external resources are loaded too- `css`,`src`, etc...)
if (event.target.readyState === "complete") {
alert("hi 2");
}
});
same for jQuery:
jQuery 也一样:
$(document).ready(function() { //same as: $(function() {
alert("hi 1");
});
$(window).load(function() {
alert("hi 2");
});
NOTE:- Don't use the below markup ( because it overwrites other same-kind declarations ) :
注意:- 不要使用以下标记(因为它会覆盖其他同类声明):
document.onreadystatechange = ...
回答by Jaime Torres
If you can use jQuery, look at load. You could then set your function to run after your element finishes loading.
如果您可以使用 jQuery,请查看load。然后,您可以将函数设置为在元素完成加载后运行。
For example, consider a page with a simple image:
例如,考虑一个带有简单图像的页面:
<img src="book.png" alt="Book" id="book" />
The event handler can be bound to the image:
事件处理程序可以绑定到图像:
$('#book').load(function() {
// Handler for .load() called.
});
If you need all elements on the current window to load, you can use
如果需要加载当前窗口上的所有元素,可以使用
$(window).load(function () {
// run code
});
回答by Hanif
I'm little bit confuse that what you means by page load completed, "DOM Load" or "Content Load" as well? In a html page load can fire event after two type event.
我有点困惑,您所说的页面加载完成、“DOM 加载”或“内容加载”是什么意思?在 html 页面加载可以在两种类型的事件之后触发事件。
DOM load: Which ensure the entire DOM tree loaded start to end. But not ensure load the reference content. Suppose you added images by the
img
tags, so this event ensure that all theimg
loaded but no the images properly loaded or not. To get this event you should write following way:document.addEventListener('DOMContentLoaded', function() { // your code here }, false);
Or using jQuery:
$(document).ready(function(){ // your code });
After DOM and Content Load: Which indicate the the DOM and Content load as well. It will ensure not only
img
tag it will ensure also all images or other relative content loaded. To get this event you should write following way:window.addEventListener('load', function() {...})
Or using jQuery:
$(window).on('load', function() { console.log('All assets are loaded') })
DOM 加载:确保从头到尾加载整个 DOM 树。但不能保证加载参考内容。假设您通过
img
标签添加了图像,因此此事件确保所有已img
加载但未正确加载图像。要获得此事件,您应该编写以下方式:document.addEventListener('DOMContentLoaded', function() { // your code here }, false);
或者使用 jQuery:
$(document).ready(function(){ // your code });
在 DOM 和内容加载之后:这也表示 DOM 和内容加载。它将确保不仅
img
标记它还将确保加载所有图像或其他相关内容。要获得此事件,您应该编写以下方式:window.addEventListener('load', function() {...})
或者使用 jQuery:
$(window).on('load', function() { console.log('All assets are loaded') })
回答by user2361682
If you wanna call a js function in your html page use onload event. The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.
如果您想在 html 页面中调用 js 函数,请使用 onload 事件。当用户代理完成加载一个窗口或 FRAMESET 中的所有框架时,就会发生 onload 事件。此属性可与 BODY 和 FRAMESET 元素一起使用。
<body onload="callFunction();">
....
</body>
回答by tsveti_iko
This way you can handle the both cases - if the page is already loaded or not:
这样您就可以处理这两种情况 - 如果页面已经加载或未加载:
document.onreadystatechange = function(){
if (document.readyState === "complete") {
myFunction();
}
else {
window.onload = function () {
myFunction();
};
};
}
回答by Ganesh Ram Ravi
Alternatively you can try below.
或者,您可以在下面尝试。
$(window).bind("load", function() {
// code here });
This works in all the case. This will trigger only when the entire page is loaded.
这适用于所有情况。这只会在加载整个页面时触发。
回答by Ryan Walker
You're best bet as far as I know is to use
据我所知,你最好的选择是使用
window.addEventListener('load', function() {
console.log('All assets loaded')
});
The #1 answer of using the DOMContentLoaded
event is a step backwards since the DOM will load before all assets load.
使用DOMContentLoaded
事件的 #1 答案是倒退,因为 DOM 将在所有资产加载之前加载。
Other answers recommend setTimeout
which I would strongly oppose since it is completely subjective to the client's device performance and network connection speed. If someone is on a slow network and/or has a slow cpu, a page could take several to dozens of seconds to load, thus you could not predict how much time setTimeout
will need.
其他答案推荐setTimeout
我强烈反对,因为它完全取决于客户端的设备性能和网络连接速度。如果某人网络速度较慢和/或 CPU 速度较慢,则页面可能需要几秒到几十秒才能加载,因此您无法预测需要多长时间setTimeout
。
As for readystatechange
, it fires whenever readyState
changes which according to MDNwill still be before the load
event.
至于readystatechange
,它会在任何readyState
更改时触发,根据MDN仍将在load
事件发生之前。
Complete
The state indicates that the load event is about to fire.
完全的
状态指示加载事件即将触发。
回答by tvrcgo
window.onload = () => {
// run in onload
setTimeout(() => {
// onload finished.
// and execute some code here like stat performance.
}, 10)
}
回答by santosh
If you're already using jQuery, you could try this:
如果你已经在使用 jQuery,你可以试试这个:
$(window).bind("load", function() {
// code here
});