为了确保文档在执行操作之前准备就绪,我执行以下操作:
(function() {
var interval = window.setInterval(function() {
if("complete" === document.readyState) {
window.clearInterval(interval);
// Some stuff
}
}, 10);
})();
如果我在代码中的某个地方通过 JavaScript 创建了一个图像,如下所示:
var image = new Image();
image.onload = function() {
// Some other stuff
};
image.src = 'some_url';
我对 document.readyState 执行的检查是否也会等待“图像”加载,或者只是等待 HTML 代码中存在的图像(并且仅加载这些图像)?
提前致谢。
最佳答案
您不需要 setInterval
。
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
您可以简单地对静态包含的图像执行此操作:
window.onload = function() {
// Some stuff
};
由于这没有考虑您稍后创建的图像,因此您可以这样做:
window.onload = function() {
var image = new Image();
image.onload = function(){
// Some stuff
};
image.src = 'some_url';
};
关于JavaScript 创建图像和 document.readyState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597893/