DOMContentLoaded blocks page loading

雨燕双飞 提交于 2020-08-04 06:51:07

问题


Please, see code:

<!-- ... -->
<head>
    <style type="text/css"> body { background: gray; } </style>
</head>
<body>
    <p>
        Firefox does not even shows blank page.
        Tab is stuck in "suggested sites" for 5 seconds.
    </p>
    <p>
        Chrome show just blank white. No text, no background. For 5 seconds.
    </p>
    <p>
        DOMContentLoaded event handler blocks page
        loading and rendering. Browser does not start
        rendering page until DOMContentLoaded
        handler function return.
    </p>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var timestamp = Date.now() + 5000; while (Date.now() < timestamp);
            // or synchronous 5 seconds XHR as an equivalent of loop
        });
    </script>
</body>
<!-- ... -->

Static html+css is more than sufficient to render content (though without IMGs, and but good layout's blocks does not depend on imgs sizes). General page layout should be shown immediately like it was always intended to. And only after rendering (or at least starting to draw it) Javsacript should run, no matter be it just controls click bindings or endless loop as in example here.

How can I run JS after static page layout is actually rendered, or at least started to appear?

(and "ready" event is not suitable here, because it is not guaranteed to fire in any reasonable time)

  • As you see from example I am not using document write nor plan to.
  • I also place script right before body closing tag
  • I am not doing any actual work right in script tag - I subsribe to the event.

Why browser prevents (blocks) user from seeing statically defined content? Does at least modern browsers can stop that nonsense?

UPD. clarification

If you use DOMContentLoaded for regular seemingly harmless tasks (subsribing to buttons events, initialising async load of other code, etc.) you in fact DO delaying user from seeing contents and that IS the real problem with DOMContentLoaded. Loop blocking here is intentional in example, just to prove that it really blocks, for those who erroneously believes DOMContentLoaded is "async"/"non-blocking" safe thing (which is not).


回答1:


Interesting and unexpected. I solved it with requestAnimationFrame(callback), like so:

function foo() {
    window.requestAnimationFrame(function() {
        window.requestAnimationFrame(function() {
            var timestamp = Date.now() + 5000; while (Date.now() < timestamp){};
            alert('now');
        });
    });
}
document.addEventListener('DOMContentLoaded', foo);


来源:https://stackoverflow.com/questions/32656594/domcontentloaded-blocks-page-loading

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!