如何延迟函数以使其完全加载

时间:2014-11-10 19:51:50

标签: javascript ajax

我有一个动态的页面,它由ajax调用填充,如下所示:

function loadpage() {
          var container = document.querySelector(".container");

          var xhr = new XMLHttpRequest();
          xhr.open('GET', ("data.html"), true);
          xhr.addEventListener("load", function(){
            container.innerHTML = xhr.response; 
            var noticeBar = document.querySelector("#noticeBar"); //this is from data.html which was jsut loaded into the DOM.        
        });
        xhr.send();
    }

当我做类似的事情时:

 function xyz(){
  loadPage().
  noticeBar.innerHTML = "bla bla bla"; //this will not work because the DOM hasnt been fully loaded

}

我正在寻找一种让它同步的方法。

1 个答案:

答案 0 :(得分:0)

loadpage()添加回调参数:

function loadpage(callback) {
      var container = document.querySelector(".container");

      var xhr = new XMLHttpRequest();
      xhr.open('GET', ("data.html"), true);
      xhr.addEventListener("load", function(){
        container.innerHTML = xhr.response; 
        var noticeBar = document.querySelector("#noticeBar"); //this is from data.html which was jsut loaded into the DOM.     
        callback(noticeBar);   
    });
    xhr.send();
}

并传入回调函数:

function xyz(){
  loadpage(
    function(noticeBar) {
      noticeBar.innerHTML = "blah blah blah";
    }
  );
}