Home > Enterprise >  How to make JavaScript execute before page load?
How to make JavaScript execute before page load?

Time:01-15

I have this code

<html>
  <head>
    <script>
      function main(){
        function loadWordlist(url){
          var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {
                 console.log('firstFunction');
              }
          };
          xhttp.open("GET", url, true);
          xhttp.send();
        }
        loadWordlist('https://www.example.com/');
      }
      main()
    </script>
  </head>
  <body>
    <script>
      console.log('secondFunction')
    </script>
  </body>
<html>

Here i am getting the content from the url And during that the browser contain loading the code and execute it

But i get secondFunction first then firstFunction And i want firstFunction to execute first then secondFunction after firstFunction finish

CodePudding user response:

Call the second function from the first function.

<html>
  <head>
    <script>
      function main(){
        function loadWordlist(url){
          var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {
                 console.log('firstFunction');
                 secondFunction();
              }
          };
          xhttp.open("GET", url, true);
          xhttp.send();
        }
        loadWordlist('https://www.example.com/');
      }
      main()
    </script>
  </head>
  <body>
    <script>
      function secondFunction() {
        console.log('secondFunction');
      }
    </script>
  </body>
<html>

If that's not possible, you can make xhttp.send() blocking. I strongly advise against it. It's bad user experience. But it's possible, and maybe there are use-cases where this is the only solution.

<html>
  <head>
    <script>
      function main(){
        function loadWordlist(url){
          var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {
                 console.log('firstFunction');
              }
          };
          xhttp.open("GET", url, false);
          xhttp.send();
        }
        loadWordlist('https://www.example.com/');
      }
      main()
    </script>
  </head>
  <body>
    <script>
      console.log('secondFunction')
    </script>
  </body>
<html>
  • Related