Javascript 页面加载完成后执行javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26954569/
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 javascript after page load is complete
提问by Matthew James Davis
I have an html page with some pre-rendered content and some yet un-rendered content. I want to display the pre-rendered content immediately, and then begin rendering the rest of the content. I am not using jQuery.
我有一个 html 页面,其中包含一些预渲染的内容和一些尚未渲染的内容。我想立即显示预渲染的内容,然后开始渲染其余的内容。我没有使用 jQuery。
See the following snippet. I have tried this various ways, including injecting my script before the closing body tag and providing my script to populate the DOM as a callback to window.onload, document.body.onload, and document.addEventListener('DOMContentLoaded'). In every case, the page does not display the pre-rendered content until the rest of the content is rendered.
请参阅以下代码段。我曾经尝试这样做的各种方式,包括结束标记之前注入我的脚本,并提供我的脚本来填充DOM的回调window.onload,document.body.onload和document.addEventListener('DOMContentLoaded')。在每种情况下,页面都不会显示预渲染的内容,直到其余内容被渲染。
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
for (var i = 0; i < 500; i++)
main.innerText += new Date();
</script>
</body>
</html>
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
document.body.onload = function() {
for (var i = 0; i < 500; i++)
main.innerText += new Date();
};
</script>
</body>
</html>
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
window.onload = function() {
for (var i = 0; i < 500; i++)
main.innerText += new Date();
};
</script>
</body>
</html>
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
document.addEventListener('DOMContentLoaded', function() {
for (var i = 0; i < 500; i++)
main.innerText += new Date();
});
</script>
</body>
</html>
One case that has worked is window.setTimeoutwith 0 timeout. However, this simply defers the function until there is nothing left to do. Is this the best practice, here?
一种有效的情况是window.setTimeout0 超时。然而,这只是将函数推迟到没有任何事情要做。这是最佳做法吗?
<html><head></head>
<body>
<header>What it is, my doge?</header>
<div id="main"></div>
<script>
var main = document.getElementById('main');
window.setTimeout(function() {
for (var i = 0; i < 500; i++)
main.innerText += new Date();
}, 0);
</script>
</body>
</html>
回答by svidgen
In terms of a bestpractice, there isn't one. In terms of a good, common, and acceptablepractices, there are a handful. You've hit one:
就最佳实践而言,没有。就良好的、常见的和可接受的做法而言,有一些。你打了一个:
setTimeout(function() { }, 1);
In this case, the function is executed within the browser's minimum timeout periodafter all other in-line processing ends.
在这种情况下,在所有其他内嵌处理结束后,该函数将在浏览器的最短超时时间内执行。
Similarly, if you want to ensure your function runs shortly after some condition is true, use an interval:
同样,如果您想确保您的函数在某些条件为 true后不久运行,请使用间隔:
var readyCheck = setInterval(function() {
if (readyCondition) {
/* do stuff */
clearInterval(readyCheck);
}
}, 1);
I've been using a similar, but more generalized solution in my own work. I define a helper function in the header:
我在自己的工作中一直在使用类似但更通用的解决方案。我在标题中定义了一个辅助函数:
var upon = function(test, fn) {
if (typeof(test) == 'function' && test()) {
fn();
} else if (typeof(test) == 'string' && window[test]) {
fn();
} else {
setTimeout(function() { upon(test, fn); }, 50);
}
}; // upon()
... and I trigger other functionality when dependencies are resolved:
...并且在解决依赖项时触发其他功能:
upon(function() { return MyNS.Thingy; }, function() {
// stuff that depends on MyNS.Thingy
});
upon(function() { return document.readyState == 'complete';}, function() {
// stuff that depends on a fully rendered document
});
Or, if you want a more authoritative goodpractice, follow Google's example. Create an external asyncscript and inject it before your first header script:
或者,如果您想要更权威的良好实践,请遵循 Google 的示例。创建一个外部async脚本并在您的第一个标头之前注入它script:
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true;
s.src = '/path/to/script.js';
var header_scripts = document.getElementsByTagName('script')[0];
header_scripts.parentNode.insertBefore(s, header_scripts);
Google's solution theoretically works on all browsers (IE < 10?) to get an external script executing as soon as possible without interfering with document loading.
Google 的解决方案理论上适用于所有浏览器(IE < 10?),以在不干扰文档加载的情况下尽快执行外部脚本。
If you want an authoritative commonpractice, check the source for jQuery's onreadysolution.
如果你想要一个权威的普遍做法,检查jQuery的源onready解决方案。
回答by Clint Powell
Depending on your browser requirements you can use the asynctag and import your script after content loads. This probably accomplishes the same thing as setTimeout(func, 0), but perhaps it's a little less hacky.
根据您的浏览器要求,您可以使用该async标签并在内容加载后导入您的脚本。这可能完成与 相同的事情setTimeout(func, 0),但也许它不那么笨拙。
See http://plnkr.co/edit/7DlNWNHnyX5s6UE8AFiU?p=preview
见http://plnkr.co/edit/7DlNWNHnyX5s6UE8AFiU?p=preview
html:
html:
...
<body>
<h1 id="main">Hello Plunker!</h1>
<script async src="script.js"></script>
</body>
...
script.js:
脚本.js:
for(var i=0; i<500; ++i) {
document.getElementById('main').innerText += new Date();
}
回答by Nick Salloum
I've used this to effect before:
我以前用过这个效果:
var everythingLoaded = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(everythingLoaded);
init(); // this is the function that gets called when everything is loaded
}
}, 10);
回答by Pedro Moreira
I think what you want to do is use an onload event on the tag. This way first the "What it is, my doge?" message will appear while the javascript is processed.
我认为您想要做的是在标签上使用 onload 事件。首先是“这是什么,我的总督?” 处理 javascript 时将出现消息。
I also set a timeout inside the loop, so you can see better the lines being added.
我还在循环内设置了超时,以便您可以更好地看到添加的行。
<html>
<head>
<script>
myFunction = function() {
for (var i = 1000; i > 0; i--) {
setTimeout(function() {
main.innerText += new Date();
}, 100);
}
};
</script>
</head>
<body onload="myFunction()">
<header>What it is, my doge?</header>
<div id="main"></div>
</body>
</html>

