放置<脚本>标签就在 </body> 之前没有按预期工作 [英] placing <script> tags right before </body> doesn't work as expected
问题描述
我正在看一个教程,其中导师建议为了改善用户体验,最好在
之前添加 标签code> ,因此脚本在页面内容完全加载后运行.
Im watching a tutorial in which the mentor suggests that in order to improve the user experience it is better to add <script>
tags right before the </body>
, so the script runs after the page content is fully loaded.
我尝试了这段代码,我希望看到hello world!"在任何脚本运行之前,但我的浏览器在其他所有内容出现之前运行 javascript(仅显示带有警告框的空白页面)
I try this block of code and I expect to see the "hello world!" before any script runs but my browser runs the javascript before everything else shows up (displays only a blank page with the alert box)
<html>
<body>
<p>hello world!</p>
<script>
alert('hey there');
</script>
</body>
</html>
我用 safari/chrome/opera 尝试了这个并得到了相同的结果.我知道我可以使用 jQuery 来解决这个问题,但有人可以解释这种行为吗?
I tried this with safari/chrome/opera and got the same result. I know I can use jQuery to solve this but can someone explain this behaviour?
感谢@T.J.Crowder,我标记了正确答案,以防万一有人对引擎盖下发生的事情感到好奇,我在这里找到了一个很好的解释:脚本在/body 之前,但在页面加载之前运行
Thanks to @T.J.Crowder , I marked the correct answer, just in case anyone is curious about what is happening under the hood I've found a good explanation here: Script is before /body but it runs before page is loaded
...所以脚本在页面内容完全加载后运行.
...so the script runs after the page content is fully loaded.
正确,它上面的所有元素都被解析并在DOM中 —但是,浏览器可能还没有机会渲染它们.给它一个这样做的机会,通过一个非常小的延迟到你的代码中.
Correct, all the elements above it are parsed and in the DOM — but, the browser may or may not have had a chance to render them yet. To give it a chance to do so, through a very small delay into your code.
<script>
setTimeout(function() {
alert('hey there');
}, 50);
</script>
</body>
现场示例:
<p>hello world!</p>
<script>
setTimeout(function() {
alert('hey there');
}, 50);
</script>
这会增加 50 毫秒的延迟 —没有什么是人类会注意到的.但是如果你想要绝对的最小延迟:
That adds a 50ms delay — nothing a human being is going to notice. But if you want the absolute minimum delay:
<script>
requestAnimationFrame(function() {
setTimeout(function() {
alert('hey there');
}, 0);
});
</script>
</body>
现场示例:
<p>hello world!</p>
<script>
requestAnimationFrame(function() {
setTimeout(function() {
alert('hey there');
}, 0);
});
</script>
更多:
不过,它们不会等待所有图像等加载完毕.如果您想等待一切(这可能是很长的路要走),请使用 window
load
事件,请参阅该链接或 此答案 示例.
Those won't wait for all images and such to load, though. If you want to wait for everything (which could be a long way), use the window
load
event, see that link or this answer for examples.
这篇关于放置<脚本>标签就在 </body> 之前没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!