How to check if DOM is ready without a framework?

前端 未结 6 1247
有刺的猬
有刺的猬 2020-11-27 12:39

The question is so like a zillion others here and on the web - How to check if DOM has loaded in Javascript? But here\'s the catch:

  • Without using a framework l
6条回答
  •  独厮守ぢ
    2020-11-27 13:12

    The document.readyState property can be used to check if the document is ready. From MDN:

    Values

    The readyState of a document can be one of following:

    • loading – The document is still loading.
    • interactive – The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading.
    • complete – The document and all sub-resources have finished loading. The state indicates that the load event is about to fire.

    Code example:

    if(document.readyState === "complete") {
        // Fully loaded!
    }
    else if(document.readyState === "interactive") {
        // DOM ready! Images, frames, and other subresources are still downloading.
    }
    else {
        // Loading still in progress.
        // To wait for it to complete, add "DOMContentLoaded" or "load" listeners.
    
        window.addEventListener("DOMContentLoaded", () => {
            // DOM ready! Images, frames, and other subresources are still downloading.
        });
    
        window.addEventListener("load", () => {
            // Fully loaded!
        });
    }
    

提交回复
热议问题