如何检查页面是否已完全加载(脚本和全部)? [英] How to check if page has FULLY loaded(scripts and all)?

查看:167
本文介绍了如何检查页面是否已完全加载(脚本和全部)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,这里有很多回答的问题.但是,我的情况有所不同,我还找不到答案.

I know, there are lots of answered questions about it here. My situation is a bit different, though, and I couldn't find an answer yet.

在页面完全加载后,我试图显示一条消息.使用$(document).ready, document.readyStateChange,我不在乎.

I'm trying to show a message after the page has fully loaded. Using $(document).ready, document.readyStateChange, I don't care.

问题在于文档已经准备好在需要执行的脚本中间.我尝试使用window.onload(和jQuery等效)进行此操作,但是它在某些图像/元素出现之前向我显示了该消息.有没有办法等待它执行然后才显示消息? (请记住,我可能需要在同一页面中多次执行该操作.)

The thing is that the document gets ready right in the middle of a script that needs to be executed. I've tried to do it with window.onload (and it's jQuery equivalent), but it shows me the message before some images/elements show up. Is there a way to wait for it to be executed and only then show up the message? (Please keep in mind that I might need to do it several times in the same page).

提前谢谢!

推荐答案

确保页面真正完成加载并非总是一件容易的事.特别是对于依靠Ajax依赖内容的页面以及其他异步加载的资产(每个资产可以独立加载,也可以与其他资产并行加载,例如图像).

Making sure a page has truly finished loading isn't always an easy job. especially for pages which rely on content via Ajax, and other assets which load asynchronously (each asset can be loaded independent and in parallel to other assets, like images for example).

创建一些全局Deferred对象(一个Promise),并确保仅在它依赖的所有内容都为就绪"后才能解决.

Create some global Deferred object (a promise) and make sure it will be resolved only after everything that it is depended on is "ready".

// start your web app code..
var p1 = new Promise();
var p2 = new Promise();
var p3 = new Promise();

// when all dependencies are done loading, means the page is truly "ready"
Promise.all([p1, p2, p3])
  .then(() => { 
       // page done loading
  });

// somewhere in the code...wait for Ajax content to load
// and resolve "p1" after the content has loaded
p1.resolve();

// somewhere in the code...wait for some other Ajax content to load
// and resolve "p2" after the content has loaded
p2.resolve();

// somewhere in the code...wait for all the images to load 
// (http://stackoverflow.com/a/1977898/104380)
// and resolve "p3"
p3.resolve();

要点是,您需要手动确保所有异步的不同部分都已完全加载.这是一个繁琐的工作,但这是一个非常可靠的解决方案.

The point is that you manually need to make sure all the different parts that are async have been fully loaded. it's a tedious work but it's a very solid solution.

这篇关于如何检查页面是否已完全加载(脚本和全部)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆