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

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


当前回答

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

为了完整起见,您可能还想将它绑定到DOMContentLoaded,现在得到了广泛的支持

document.addEventListener("DOMContentLoaded", function(event){
  // your code here
});

更多信息:https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

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

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

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

通过Javascript

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

通过Jquery

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

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

<body onload="somecode();" >

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

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