Javascript: Have body onload function wait until scripts have completed

纵然是瞬间 提交于 2019-12-05 22:13:50

What you could do is keep your page content in a div that is initially styled with display:none. Then when your javascript code finishes, update the style on the div to display:block, e.g.:

<html>
    <head>
        ...
        <style type="text/css">
            html, body, #body {
                height: 100%;
                width: 100%;
                padding: 0;
                margin: 0;
            }
            #body {
                display: none;
            }
        </style>
        <script type="text/javascript">
            function myFunc() {
                ...
                getElementById('body').style.display = 'block';
            }
        </script>
    </head>
    <body onload="myFunc();">
        <div id="body>
            ...
        </div>
    </body>
</html>

Then Bob's your uncle: the page looks like it has delayed loading until after your script is finished.

Functions that are called in the <body> tag's onLoad event are only fired when the DOM is loaded (however it does not wait for external dependencies such as JavaScript files and CSS to load), so you can be sure that when your someFunc() function is called, (if attached to the <body> tag's onLoad event) the elements in the page have been loaded. If you want to access a DIV that is loaded in the page then you can be sure that it will have loaded when your someFunc() function is called.

To solve your problem you could wrap then content of your page in a DIV, with the display of it set initially to none. Then when the page has loaded, your someFunc() function is called. When it has finished executing, you can set the display of your wrapper DIV to block, so that it is visible to the user.

However, make sure that you make the user aware that the page is loading, and you do not simply show them a blank screen whilst your JavaScript is loading.

The body's onLoad function is triggered when the DOM has completed loading - which implies that all HTML elements have been fully loaded. So your onload function itself should assume that everything is loaded and ready to go, since its very execution is under those guidelines.

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