javascriptreadystate

Equivalent of readystatechange after changing page content using javascript


I am modifying dynamically a part of page (which is loaded only once), using javascript. I am looking for an equivalent of readystatechange event that will be triggered when all images, fonts, ... are loaded after the partial page change.

How can I achieve that?

Note: Reloading the full page is not an option for performances reasons

I am using vanilla JS:

containerElement.innerHTML = htmlString;

Solution

  • The best you can do, if you're doing everything manually with vanilla JS, is detect when child elements that support the load event (images, videos, etc.) all finish loading. It's not a perfect representation of the DIV being loaded, but maybe it'll be close enough for your purposes.

    So just after you set the innerHTML of your DIV, call a function that does something like this:

    function onDivLoaded(div, callback) {
        const loadable_types = ['img', 'video', 'frame', 'frameset', 'iframe', 'link', 'script'];
        const total = {};
        const loaded = {};
    
        function tryCallback(type) {
            ++loaded[type];
            const hasMore = loadable_types.some(type => loaded[type] < total[type]);
            if (!hasMore) { callback(div); }
        }
    
        loadable_types.forEach(type => {
            const els = div.getElementsByTagName(type);
            total[type] = els.length;
            loaded[type] = 0;
            els.forEach(element => {
                element.addEventListener('load', () => tryCallback(type));
                element.addEventListener('error', () => tryCallback(type));
            });
        });
    }
    

    So basically, after setting the innerHTML, you'd call onDivLoaded and pass it the container DIV and the callback to run when it's loaded. This will then attach load and error handlers to every DOM element inside the DIv that supports those events, and whenever one fires, it'll track how many are loaded out of how many total. When 100% of the loadable elements are loaded, it'll fire the callback.