当页面完全加载时,我需要执行一些JavaScript代码。这包括像图像这样的东西。
我知道您可以检查DOM是否准备好了,但我不知道这是否与页面完全加载时相同。
当页面完全加载时,我需要执行一些JavaScript代码。这包括像图像这样的东西。
我知道您可以检查DOM是否准备好了,但我不知道这是否与页面完全加载时相同。
当前回答
为了完整起见,您可能还想将它绑定到DOMContentLoaded,现在得到了广泛的支持
document.addEventListener("DOMContentLoaded", function(event){
// your code here
});
更多信息:https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
其他回答
这里有一个用PrototypeJS来做的方法:
Event.observe(window, 'load', function(event) {
// Do stuff
});
你可能想用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。
2019年更新:这是对我有用的答案。因为我需要多个ajax请求来触发并首先返回数据来计数列表项。
$(document).ajaxComplete(function(){
alert("Everything is ready now!");
});
试试这段代码
document.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
详情请访问https://developer.mozilla.org/en-US/docs/DOM/document.readyState