Unable to load HTML before Javascript

前端 未结 2 371
南笙
南笙 2020-12-20 23:24

I am new to Javascript, and know how can I load html before javascript is executed.

I did check the questions on stackoverflow and tried to implement the solutions g

相关标签:
2条回答
  • 2020-12-20 23:45

    First of all, I suggest to read this article. Now, based on the source of this document, the best way (using only Javascript) to wait for the document to fully render before executing some code, will be using a listener on the load event of the window element, like this:

    window.addEventListener('load', function() {
      // Everything has loaded!
    });
    

    I have added an image to your code just to test how this approach waits the image to render before prompt to the user:

    <h1>Age Calculator</h1>
    <p>Enter your age and find how many days you have been alive</p>
    <img src="https://via.placeholder.com/500?text=Test+Image">
    
    <script>
    
    function cal()
    {
        var age = prompt("How old are you?");
        var days = age * 365.25;
        alert("You are approx " + days + " days");
    }
    
    window.addEventListener('load', function()
    {
        // Everything has been rendered and loaded!
        cal();
    });
    
    </script>

    0 讨论(0)
  • 2020-12-20 23:56

    The problem is that prompt and similar functions like alert block the browser - they prevent rendering until the pop-up box has been submitted or canceled.

    <h1>Age Calculator</h1>
    <p>Enter your age and find how many days you have been alive</p>
    <script>
      var age = prompt("How old are you?");
    </script>

    If you want to make sure the HTML displays before the prompt comes up, you might use setTimeout, giving the browser a chance to paint the HTML before the prompt gets called:

    <h1>Age Calculator</h1>
    <p>Enter your age and find how many days you have been alive</p>
    <script>
      setTimeout(() => {
        var age = prompt("How old are you?");
      });
    </script>

    But an even better solution would be to use a proper modal, such as an input box with a submit button, which won't block the browser. (best to never use alert, prompt, and confirm if at all possible)

    0 讨论(0)
提交回复
热议问题