document.readyState not working in Firefox and Chrome

╄→尐↘猪︶ㄣ 提交于 2019-12-01 00:40:56
gkalpak

NOTE: In order to be able to access the document of an iframe and thus it's readyState, you need to have access to the domain in the iframe (regadless of the use of jQuery).
For more info, take a look here.


You could do it using the iframe's contentWindow property (no jQuery required).
Note that, in order to access the iframe's document, you have to add the element to the DOM first (e.g. using window.document.appendChild()).

Sample code:

var businessDownl = document.createElement('iframe');
document.body.appendChild(businessDownl);
...
var state = businessDownl.contentWindow.document.readyState;

See, also, this short demo.
[Tested on latest versions of Firefox and Chrome.]

(Notice that, because the iframe loads quickly, sometimes you see only "completed", sometimes "loading" and "completed" - once I was even lucky enough to see "uninitialized" too :D).

If you just want to wait until the document is ready there is no need to keep checking - you can listen for the event:

var whenReady = function(callback) {
  if (document.readyState === 'complete') callback(); // check not already loaded prior to this function being called
  else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback); // for standards compliant browsers (including IE 9+)
  else if (document.attachEvent) document.attachEvent('onreadystatechange', callback); // for IE 8
};

whenReady(alert('loaded'));

The only downside of this technique is that it only supports IE 8 and later. Libraries such as JQuery offer better legacy browser support and a cleaner syntax:

$(function() {
  // anything here will execute once the dom is ready
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!