【问题标题】:How do I load an html document after a certain few javascript instructions have executed?在执行了某些 javascript 指令后,如何加载 html 文档?
【发布时间】:2018-02-17 14:05:16
【问题描述】:

我正在使用 API 在页面上显示一些数据。所以我创建了一个 XMLHttpRequest 对象,设置 URL 并发送请求以获取要显示的数据。 现在,当我加载页面时,它会在我获得实际数据之前显示占位符文本一秒钟。我认为有延迟,因为我还将 JSON 转换为对象然后显示。

那么有没有办法解决这个问题。我认为我可能无法减少 API 获取造成的延迟。那么我可以让我的页面在我得到数据之前不加载吗?

    request.onload = function() {
          var obj;
          obj = JSON.parse(request.response);
          var str = "stock";
          for(var i = 0; i < 10; ++i)
          {
          //Here I set the innderHTML of a list with the API data.
          }
      };

【问题讨论】:

标签: javascript html api document


【解决方案1】:

正常行为之一是设置加载程序并正确设置其显示状态。看看下面的问题。 Show loading image while $.ajax is performed

【讨论】:

    【解决方案2】:

    只需使用适当的全局事件处理程序:onreadystatechange

    var xhr = new XMLHttpRequest(),
        method = "GET",
        url = "https://developer.mozilla.org/";
    
    xhr.open(method, url, true);
    xhr.onreadystatechange = function () {
      if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        console.log(xhr.responseText);
    
        // your code here
    
    
      }
    };
    xhr.send();
    

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange

    【讨论】:

      猜你喜欢
      • 2011-09-01
      • 2015-12-09
      • 2011-09-26
      • 1970-01-01
      • 2012-10-23
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多