The understanding of the domReady

DomReady is an alternate name for an event called DOMContentLoaded, which is triggered when the initial HTML document has been fully loaded and parsed, without waiting for the stylesheet, image, and subframe to be fully loaded.

describe

Browser renderingDOMThe structure has a certain order

Browsers render DOM structures in a certain order, and while implementations vary from browser to browser, the basic flow is generally the same:

  • Top down, first parseHTMLTag, generateDOM Tree.
  • In the analysis to<link>or<style>Tags, start parsingCSSTo generate theCSSOM, the value of note is resolved at this timeHTMLTags and parsingCSSIt is executed in parallel.
  • When faced with<script>The browser immediately starts parsing the script and stops parsing the document because the script might changeDOMwithCSS, continue parsing will waste resources, so should be<script>The label on the<body></body>After.
  • whenDOM TreewithCSSOMAfter generation, they are combined for layout, and their size and location are calculated to form an internal representation model that can represent all the information, which can be called a rendering treerender tree.
  • Draw the entire page based on the calculated information, the system will traverse the render tree, and callpaintMethod to display the content on the screen.

Parsing in the browserDOMThere are blocking processes in the structure:

  • parsingJavaScriptBlocking the browser’s parsing process, specifically parsing the rendering process and parsingJavaScriptThe process is mutually exclusive.
  • CSSParsing is loaded without blockingDOMTree parsing, these two parsing processes can be parallel, butCSSLoading process is not allowedJavaScriptAnalytical, that is to sayCSSIt will block during loadingJavaScriptIn addition because of generationRender TreeThe need whenCSSOMAnd so onDOM TreeAnalysis completed andCSSOMThe build will not continue until it is completeRender Tree.
  • parsingHTMLThe structure also does not blockCSSThe process of parsing is also not the sameJavaScriptThe parsing process is executed in parallel, andDOM TreeParsing is not completed whileCSSOMIt also does not continue to build when it is finishedRender Tree.
  • Loaded asynchronously<script>Tags are not blockingDOMParsed, of course, it won’t blockDOMContentLoadedEvent, but still blocksloadEvent trigger.

DOMContentLoadedEvents andloadEvent trigger timing:

  • When the initialHTMLOnce the document is fully loaded and parsed,DOMContentLoadedEvents are triggered without waiting for the stylesheet, image, and subframe to be fully loaded. Regarding the timing of the trigger, if all of the documents areHTMLwithCSStheDomContentLoadedEvents don’t have to waitCSSLoading can be triggered; whenJsAll inCSSbeforeDomContentLoadedEvents don’t have to waitCSSLoad can be triggered, of course parsingCSSwithDOMYou have to wait aheadJsHaving been resolved; whenJsinCSSThen, thenDomContentLoadedEvents need to wait untilCSSwithJsCan trigger only after loading, as mentioned aboveCSSThe load will blockJsLoad, whileJsThe tag itself belongsDOMStructure that must wait for its load to complete before firingDomContentLoadedEvents; Asynchronously loaded<script>Tags don’t blockDOMContentLoadedEvents.
  • Fires when the entire page and all dependent resources such as stylesheets and images have finished loadingloadEvents. Do not use dynamic loading<iframe>It also clogsloadEvent, and even asynchronously loaded<script>Tags also blockloadEvents.

To rearrange the page loading process under various conditions, the main point isDOMContentLoadedEvents andloadEvent trigger timeline:

  • Top down, first parseHTMLTag, generateDOM TreeAt this time,document.readyState = "loading".
  • In the analysis to<link>or<style>Tags, start parsingCSSTo generate theCSSOM, the value of note is resolved at this timeHTMLTags and parsingCSSIt is executed in parallel.
  • Resolve to not set asynchronous loading<script>Block document parsing and waitJsAfter the script is loaded and executed, the document is parsed.
  • Parsing to asynchrony<script>Do not block parsing the document, continue parsing down,deferAttributes can makeJsFiles waiting forDOM TreeExecute after the build is complete, andasyncAttributes can makeJsFiles are executed immediately after downloading.
  • If external resources such as images need to be loaded when parsing documents, parse this node first, according tosrcCreate load threads, load image resources asynchronously, and parse documents without blocking. Of course, browsers have restrictions on the maximum number of threads a domain can open.
  • The document has been parsed,document.readyState = "interactive".
  • Set todeferProperties of the<script>The script starts to execute in sequence.
  • The triggerDOMContentLoadedEvents.
  • Wait to set toasyncProperties of the<script>And pictures and<iframe>Wait until the page is fully loaded.
  • loadEvent trigger,document.readyState = "complete".

call

There are times when we want to intervene with the DOM as soon as possible, and it’s more appropriate to call the DOMContentLoaded event, which needs to be handled in a compatible manner to handle various browsers.

  • To supportDOMContentLoadedBrowser usageDOMContentLoadedEvents.
  • If it’s less than525Version of theWebkitThrough pollingdocument.readyStateTo implement.
  • For older versionsIEBrowser usageDiego PeriniFamous for discoveryhack.
/* https://www.cnblogs.com/JulyZhang/archive/2011/02/12/1952484.html */
/* * Register the browser's DOMContentLoaded event * @param {Function} onReady [required] The Function to be executed when the DOMContentLoaded event is triggered * @param {Object} config Optional configuration item */
function onDOMContentLoaded(onready, config) {
    // The browser detects the relevant object, in order to save the code is not implemented, the actual use of the need to implement.
    //var Browser = {};
    // Set whether to use DOMContentLoaded under FF (certain scenarios under FF2 are buggy)
    this.conf = {
        enableMozDOMReady: true
    };
    if (config)
        for (var p in config)
            this.conf[p] = config[p];
    var isReady = false;

    function doReady() {
        if (isReady) return;
        // Make sure onReady is executed only once
        isReady = true;
        onready();
    }
    /*IE*/
    if (Browser.ie) {
        (function() {
            if (isReady) return;
            try {
                document.documentElement.doScroll("left");
            } catch (error) {
                setTimeout(arguments.callee, 0);
                return; } doReady(); }) ();window.attachEvent('onload', doReady);
    }
    /*Webkit*/
    else if (Browser.webkit && Browser.version < 525) {(function() {
            if (isReady) return;
            if (/loaded|complete/.test(document.readyState))
                doReady();
            else
                setTimeout(arguments.callee, 0); }) ();window.addEventListener('load', doReady, false);
    }
    /*FF Opera high webkit other */
    else {
        if(! Browser.ff || Browser.version ! =2 || this.conf.enableMozDOMReady)
            document.addEventListener("DOMContentLoaded".function() {
                document.removeEventListener("DOMContentLoaded".arguments.callee, false);
                doReady();
            }, false);
        window.addEventListener('load', doReady, false); }}Copy the code

reference

https://juejin.cn/post/6844903667733118983
https://juejin.cn/post/6844903535314731021
https://juejin.cn/post/6844903623583891469
https://juejin.cn/post/6844904072340832264
https://juejin.cn/post/6844904176569286669
https://www.cnblogs.com/caizhenbo/p/6679478.html
https://www.cnblogs.com/rubylouvre/p/4536334.html
https://developer.mozilla.org/zh-CN/docs/Web/Events/DOMContentLoaded
https://gwjacqueline.github.io/%E5%BC%82%E6%AD%A5%E5%8A%A0%E8%BD%BDjs/
Copy the code