Page load event -- DOMContentLoaded

Keywords: Javascript IE JQuery

The difference between DOMContentLoaded and window.onload

When the page is fully loaded, it will trigger window.onload event. We know that we can use window.onload event to trigger and execute javascript scripts that need to be loaded before the page can be executed. But if the page contains many style files, picture files, sub-frame pages (iframe), onload event will be delayed to load these files. Successful execution is sometimes not what we need. For example, if we want to know how long it takes for a page to complete from acceptance to dom tree parsing, then onload events are not suitable.

DOMContentLoaded comes out at this time. It is defined as: when the page document is loaded and parsed, it will start the DOMContentLoaded event immediately, instead of waiting for the loading of style files, picture files and sub-frame pages.

Example

<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");
  });
</script>

Compatibility

DOMContentLoaded currently supports all mainstream browsers, as well as IE9. See more. can I use?

If IE is compatible, two additional events are required. In IE8, the readystatechange event can be used to monitor whether the DOM document has been loaded. In earlier versions of IE, the state can be monitored by executing document.documentElement.doScroll('left') every other time with try/catch, because this code will be thrown before the DOM load is completed. throw an error

Based on the above explanation, we can write an IE-compatible DOM Content Loaded event from

// if IE
function IEContentLoaded (w, fn) {
    var d = w.document, done = false,
    // only fire once
    init = function () {
        if (!done) {
            done = true;
            fn();
        }
    };
    // polling for no errors
    (function () {
        try {
            // throws errors until after ondocumentready
            d.documentElement.doScroll('left');
        } catch (e) {
            setTimeout(arguments.callee, 50);
            return;
        }
        // no errors, fire
        init();
    })();
    // trying to always fire before onload
    d.onreadystatechange = function() {
        if (d.readyState == 'complete') {
            d.onreadystatechange = null;
            init();
        }
    };
}

EXPERIMENTAL SEGMENTATION LINE

At present, many libraries have implemented compatible page loading completion events. Probably the idea is to judge whether document. readyState==='complete'is true or not, and to execute the script directly if true, otherwise the script will be bound to the page loading completion events. Then, according to whether the document has addEventListener, we can distinguish the mainstream browser from IE browser, because IE9 and later base. This standard is the same as the mainstream browser, so it is mainly used to distinguish IE8 and below, DOMContentLoaded + window.load for mainstream browsers, and onreadystatechange + window.onload + doScroll for IE8 and below.

Note here that the onreadstatechange event is not reliable. If there are pictures on the page, it may trigger after the onload event. Normally, it can only correctly execute the page without binary resources or when it is very small or cached as an alternative.

function domReady(fn) {
    var ready = false,
        top = false,
        doc = window.document,
        root = doc.documentElement,
        modern = doc.addEventListener,
        add = modern ? 'addEventListener' : 'attachEvent',
        del = modern ? 'removeEventListener' : 'detachEvent',
        pre = modern ? '' : 'on',
        init = function(e) {
            if (e.type === 'readystatechange' && doc.readyState !== 'complete') return;
            (e.type === 'load' ? window : doc)[del](pre + e.type, init, false);
            if (!ready && (ready = true)) fn.call(window, e.type || e);
        },
        poll = function() {
            try {
                root.doScroll('left');
            } catch(e) {
                setTimeout(pull, 50);
                return;
            }
            init('poll');
        };
        
        if (doc.readyState === 'complete') fn.call(window, 'lazy');
        else {
            if (!modern && root.doScroll) {
                try {
                    top = !window.frameElement;
                } catch(e) {}
                if (top) poll();
            }
            doc[add](pre + 'DOMContentLoaded', init, false);
            doc[add](pre + 'readystatechange', init, false);
            window[add](pre + 'load', init, false);
        }
}

Related events

Expand

Posted by Havenot on Thu, 11 Apr 2019 16:06:31 -0700