简体   繁体   中英

How to make JavaScript execute before page load?

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM