簡體   English   中英

如何讓 JavaScript 在頁面加載前執行?

[英]How to make JavaScript execute before page load?

我有這個代碼

<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>

在這里,我從 url 獲取內容,在此期間瀏覽器包含加載代碼並執行它

但是我先得到secondFunction ,然后得到firstFunction我希望firstFunction先執行,然后在secondFunction完成后執行firstFunction

從第一個 function 撥第二個 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>

如果那不可能,您可以使xhttp.send()阻塞。 我強烈反對它。 這是糟糕的用戶體驗。 但這是可能的,也許在某些用例中這是唯一的解決方案。

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM