JavaScript 创建图像和 document.readyState

标签 javascript image onload readystate

为了确保文档在执行操作之前准备就绪,我执行以下操作:

(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

From the MDN :

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/

相关文章:

javascript - 使用 javascript 为用户提供图像下载

c# - 在图像按钮中加载图像

javascript - 激活:focus when the page loads with Javascript

javascript - 在 Javascript 中格式化用户发送的聊天消息

javascript - 在 mx :HTML's iframe (and read it's value cross-domain) 中设置 `top.location === location`

image - 使用 Paradox 在 Delphi 7 中实时将 BMP 转换为 JPG

javascript - 如何在 window.onload 事件后使用 reactjs/nextjs 加载脚本

javascript - 尝试使用 jquery 加载随机图像 - 不起作用

javascript - 使用 nvidia GPU 在 Windows x64 上的 Chrome 中 Webgl 闪烁

javascript - 为AngularJS中的常量定义函数