当页面完全加载时,我需要执行一些JavaScript代码。这包括像图像这样的东西。

我知道您可以检查DOM是否准备好了,但我不知道这是否与页面完全加载时相同。


当前回答

你可能想用window。onload,因为文档表明它不会被触发,直到DOM准备好和页面中的所有其他资产(图像等)被加载。

其他回答

尝试这只运行后,整个页面已加载

通过Javascript

window.onload = function(){
    // code goes here
};

通过Jquery

$(window).bind("load", function() {
    // code goes here
});

窗外。Onload事件将在加载所有内容时触发,包括图像等。

如果你想要你的js代码尽可能早地执行,你会想要检查DOM就绪状态,但你仍然需要访问DOM元素。

在使用现代javascript(>= 2015)的现代浏览器中,您可以在脚本标记中添加type="module",脚本中的所有内容将在整个页面加载后执行。例句:

<script type="module">
  alert("runs after") // Whole page loads before this line execute
</script>
<script>
  alert("runs before")
</script>

旧的浏览器也能理解nomodule属性。就像这样:

<script nomodule>
  alert("tuns after")
</script>

更多信息请访问javascript.info。

2019年更新:这是对我有用的答案。因为我需要多个ajax请求来触发并首先返回数据来计数列表项。

$(document).ajaxComplete(function(){
       alert("Everything is ready now!");
});

这里有一个用PrototypeJS来做的方法:

Event.observe(window, 'load', function(event) {
    // Do stuff
});