how to know the first ready state of DOM

陌路散爱 提交于 2019-12-10 22:40:04

问题


i am trying to get the first ready state of the DOM. the second, third, etc is not interesting me, but the first one. is there any trick to get the first ready state of DOM?

$(document).ready(function() {
  // is it the first ready state?
});

回答1:


Ah, you're using jQuery. Have a look at the docs: There is only one ready event! I will never fire multiple times. Internally, this is even handled with a Promise, so it cannot fire multiple times.




回答2:


There are 4 readyState possible values:

  • uninitialized - Has not started loading yet
  • loading - Is loading
  • interactive - Has loaded enough and the user can interact with it
  • complete - Fully loaded

To see it's value use this code:

document.onreadystatechange = function () {
    if (document.readyState === YourChoice) {
        // ...
    }
}

I could not catch the uninitialized readyState. (but why should I need it?)

If you need a listener for complete load of the DOM, use:

document.addEventListener('DOMContentLoaded', YourListener);

or

document.addEventListener('load', YourListener);

or even

window.onload = YourListener;

for jquery:

$(document).on("DOMContentLoaded", function() { });

or

$(document).on("load", function() { });

or

$(window).on("load", function() { });


来源:https://stackoverflow.com/questions/13859080/how-to-know-the-first-ready-state-of-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!