Javascript: have an onload function to load until scripts complete

I have some functions that I call, and they take some time (milliseconds), but I do not want the page to be displayed until these functions are completed. Right now, I can say that the page is loading, and then the scripts complete.

Now I am calling functions in the onload body.

Also, another problem that may arise is that I need to access div elements in html content, can I do this in my onload (getElementById ('somDiv') function?

Here is the workflow.

  • Make a call to getElementById ('someDiv') to get the item from the page.

  • Call the someFunc function, this function is in the body onload = someFunc ()

  • Wait until someFunc ends

  • Show page to user after completion of my function.

+3
source share
3 answers

What you can do is save the contents of your page to the divone that was originally created with display:none. Then, when your JavaScript code ends, update the style to divto display:block, for example:

<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 is your uncle: the page looks like it postponed loading until your script ends.

+5
source

, <body> onLoad, DOM ( , JavaScript CSS), , someFunc() ( <body> onLoad), . DIV, , , someFunc().

, DIV, display none. , , someFunc(). , display DIV block, .

, , , , JavaScript.

+1

The body onLoad function is triggered when the DOM has finished loading - this means that all HTML elements are fully loaded. Therefore, your onload function itself must assume that everything is loaded and ready to work, since its execution is carried out in accordance with these recommendations.

0
source

Source: https://habr.com/ru/post/1709793/


All Articles