Javascript - 如何检测文档是否已加载(IE 7/Firefox 3)

发布于 2024-07-24 05:56:20 字数 563 浏览 9 评论 0原文

我想在文档加载后调用函数,但文档可能尚未完成加载,也可能尚未完成。 如果它确实加载了,那么我就可以调用该函数。 如果它没有加载,那么我可以附加一个事件监听器。 在 onload 已经触发后,我无法添加事件监听器,因为它不会被调用。 那么如何检查文档是否已加载呢? 我尝试了下面的代码,但它并不完全有效。 有任何想法吗?

var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if (body && body.readyState == 'loaded') {
    DoStuffFunction();
} else {
    // CODE BELOW WORKS
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}

I want to call a function after a document loads, but the document may or may not have finished loading yet. If it did load, then I can just call the function. If it did NOT load, then I can attach an event listener. I can't add an eventlistener after onload has already fired since it won't get called. So how can I check if the document has loaded? I tried the code below but it doesn't entirely work. Any ideas?

var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if (body && body.readyState == 'loaded') {
    DoStuffFunction();
} else {
    // CODE BELOW WORKS
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

再见回来 2024-07-31 05:56:20

不需要 galambalazs 提到的所有代码。 在纯 JavaScript 中执行此操作的跨浏览器方法就是简单地测试 document.readyState

if (document.readyState === "complete") { init(); }

这也是 jQuery 的做法。

根据 JavaScript 的加载位置,这可以在一个时间间隔内完成:

var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        clearInterval(readyStateCheckInterval);
        init();
    }
}, 10);

事实上,document.readyState 可以具有三种状态:

文档加载时返回“loading”,解析完成后返回“interactive”,但仍在加载子资源,加载后返回“complete”。
-- Mozilla 开发者网络的 document.readyState

因此,如果您只需要 DOM准备好了,检查 document.readyState === "interactive"。 如果您需要准备好整个页面(包括图像),请检查 document.readyState ===“complete”

There's no need for all the code mentioned by galambalazs. The cross-browser way to do it in pure JavaScript is simply to test document.readyState:

if (document.readyState === "complete") { init(); }

This is also how jQuery does it.

Depending on where the JavaScript is loaded, this can be done inside an interval:

var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        clearInterval(readyStateCheckInterval);
        init();
    }
}, 10);

In fact, document.readyState can have three states:

Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.
-- document.readyState at Mozilla Developer Network

So if you only need the DOM to be ready, check for document.readyState === "interactive". If you need the whole page to be ready, including images, check for document.readyState === "complete".

白昼 2024-07-31 05:56:20

不需要图书馆。 顺便说一句,jQuery 使用这个脚本有一段时间了。

http://dean.edwards.name/weblog/2006/06/again/

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;

No need for a library. jQuery used this script for a while, btw.

http://dean.edwards.name/weblog/2006/06/again/

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;
鸠魁 2024-07-31 05:56:20

您可能想使用 jQuery 之类的东西,它使 JS 编程更容易。

比如:

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

似乎会做你想做的事。

You probably want to use something like jQuery, which makes JS programming easier.

Something like:

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

Would seem to do what you are after.

忆梦 2024-07-31 05:56:20
if(document.readyState === 'complete') {
    DoStuffFunction();
} else {
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}
if(document.readyState === 'complete') {
    DoStuffFunction();
} else {
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}
有深☉意 2024-07-31 05:56:20

如果您确实希望此代码在 load 时运行,而不是在 domready 时运行(即您还需要加载图像),那么不幸的是,ready 函数无法为您执行此操作。 我通常只是做这样的事情:

包含在文档javascript中(即总是在onload触发之前调用):

var pageisloaded=0;
window.addEvent('load',function(){
 pageisloaded=1;
});

然后你的代码:(

if (pageisloaded) {
 DoStuffFunction();
} else {
 window.addEvent('load',DoStuffFunction);
}

或者你的偏好框架中的等效代码。)我使用此代码为未来页面预先缓存javascript和图像。 由于我获得的内容根本不用于此页面,因此我不希望它优先于图像的快速下载。

也许有更好的方法,但我还没有找到。

If you actually want this code to run at load, not at domready (ie you need the images to be loaded as well), then unfortunately the ready function doesn't do it for you. I generally just do something like this:

Include in document javascript (ie always called before onload fired):

var pageisloaded=0;
window.addEvent('load',function(){
 pageisloaded=1;
});

Then your code:

if (pageisloaded) {
 DoStuffFunction();
} else {
 window.addEvent('load',DoStuffFunction);
}

(Or the equivalent in your framework of preference.) I use this code to do precaching of javascript and images for future pages. Since the stuff I'm getting isn't used for this page at all, I don't want it to take precedence over the speedy download of images.

There may be a better way, but I've yet to find it.

最偏执的依靠 2024-07-31 05:56:20

Mozila Firefox 表示 onreadystatechangeDOMContentLoaded 的替代方案。

// alternative to DOMContentLoaded
document.onreadystatechange = function () {
    if (document.readyState == "complete") {
        initApplication();
    }
}

DOMContentLoaded 中,Mozila 的文档说:

文档加载完毕后,会触发 DOMContentLoaded 事件
完全加载和解析,无需等待样式表、图像、
和子帧来完成加载(加载事件可用于检测
一个完全加载的页面)。

我认为 load 事件应该用于完整的文档+资源加载。

Mozila Firefox says that onreadystatechange is an alternative to DOMContentLoaded.

// alternative to DOMContentLoaded
document.onreadystatechange = function () {
    if (document.readyState == "complete") {
        initApplication();
    }
}

In DOMContentLoaded the Mozila's doc says:

The DOMContentLoaded event is fired when the document has been
completely loaded and parsed, without waiting for stylesheets, images,
and subframes to finish loading (the load event can be used to detect
a fully-loaded page).

I think load event should be used for a full document+resources loading.

二智少女猫性小仙女 2024-07-31 05:56:20

上面使用 JQuery 的方法是最简单也是最常用的方法。 但是,您可以使用纯 javascript,但尝试在头部定义此脚本,以便在开始时读取它。 您正在寻找的是 window.onload 事件。

下面是我创建的一个用于运行计数器的简单脚本。 计数器在 10 次迭代后停止

window.onload=function()
{
    var counter = 0;
    var interval1 = setInterval(function()
    { 
        document.getElementById("div1").textContent=counter;
        counter++; 
        if(counter==10)
        {
            clearInterval(interval1);
        }
    },1000);

}

The above one with JQuery is the easiest and mostly used way. However you can use pure javascript but try to define this script in the head so that it is read at the beginning. What you are looking for is window.onload event.

Below is a simple script that I created to run a counter. The counter then stops after 10 iterations

window.onload=function()
{
    var counter = 0;
    var interval1 = setInterval(function()
    { 
        document.getElementById("div1").textContent=counter;
        counter++; 
        if(counter==10)
        {
            clearInterval(interval1);
        }
    },1000);

}
金橙橙 2024-07-31 05:56:20

尝试这个:

var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if ((body && body.readyState == 'loaded') || (body &&  body.readyState == 'complete') ) {
    DoStuffFunction();
} else {
    // CODE BELOW WORKS
    if (window.addEventListener) {
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload',DoStuffFunction);
    }
}

Try this:

var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if ((body && body.readyState == 'loaded') || (body &&  body.readyState == 'complete') ) {
    DoStuffFunction();
} else {
    // CODE BELOW WORKS
    if (window.addEventListener) {
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload',DoStuffFunction);
    }
}
苍风燃霜 2024-07-31 05:56:20

我有其他解决方案,我的应用程序需要在创建 MyApp 的新对象时启动,所以它看起来像:

function MyApp(objId){
     this.init=function(){
        //.........
     }
     this.run=function(){
          if(!document || !document.body || !window[objId]){
              window.setTimeout(objId+".run();",100);
              return;
          }
          this.init();
     };
     this.run();
}
//and i am starting it 
var app=new MyApp('app');

据我所知,它适用于所有浏览器。

I have other solution, my application need to be started when new object of MyApp is created, so it looks like:

function MyApp(objId){
     this.init=function(){
        //.........
     }
     this.run=function(){
          if(!document || !document.body || !window[objId]){
              window.setTimeout(objId+".run();",100);
              return;
          }
          this.init();
     };
     this.run();
}
//and i am starting it 
var app=new MyApp('app');

it is working on all browsers, that i know.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文