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

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


当前回答

GlobalEventHandlers mixin的onload属性是一个事件 窗口加载事件的处理程序,XMLHttpRequest,元素, 等,它在资源加载时触发。

所以基本上javascript已经有onload方法在窗口上执行,哪个页面完全加载,包括图像…

你可以做一些事情:

var spinner = true;

window.onload = function() {
  //whatever you like to do now, for example hide the spinner in this case
  spinner = false;
};

其他回答

你可能想用window。onload,因为文档表明它不会被触发,直到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。

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

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

GlobalEventHandlers mixin的onload属性是一个事件 窗口加载事件的处理程序,XMLHttpRequest,元素, 等,它在资源加载时触发。

所以基本上javascript已经有onload方法在窗口上执行,哪个页面完全加载,包括图像…

你可以做一些事情:

var spinner = true;

window.onload = function() {
  //whatever you like to do now, for example hide the spinner in this case
  spinner = false;
};

Javascript使用onLoad()事件,将等待页面加载之前执行。

<body onload="somecode();" >

如果你正在使用jQuery框架的文档准备函数,代码将在DOM加载时加载,在页面内容加载之前加载:

$(document).ready(function() {
    // jQuery code goes here
});