Document.readystate正在谈论正在加载的Google Maps画布图像

时间:2017-05-23 21:15:07

标签: javascript domdocument msdn readystate onreadystatechange

我正在iframe中打印包含google maps API v3地图的页面。我实现了以下代码,以确保在打印iframe之前页面已完全加载。

/**
*    Auto print the page once the full document has finished loading
*/
function checkDocumentStateChange(documentElement) {

  var document = documentElement;
  console.log('Document ReadyState: ' + document.readyState);
  document.onreadystatechange = function () {

     console.log('Document ReadyState: ' + document.readyState);

     if (document.readyState === 'complete') {
        console.log("Document fully loaded!");
        console.log("Printing report from within iframe");
        setTimeout(function () {
           window.print();

           var requestOrigin = '@viewModel.RequestOrigin';
           if(!!requestOrigin) {
              // Tell the parent window that the print has occurred, so it can prepare to cleanup and remove this iframe
              console.log("Send postMessage: secret");
              parent.postMessage('secret', requestOrigin);
           }
        }, 500);

     }
  }

}

然而,即使在document.readystate === 'complete'为真的情况下延迟500毫秒,通常页面也会打印灰色/空白谷歌地图画布,没有图像。

如果我再次点击window.print()而不重新加载页面,那么它会按预期打印出包含所有地图图像的iframe。所以文件就绪状态正在说谎。

我可以做些什么来解决这个问题,除了延迟更长的延迟(我不想这样做,因为它会惩罚人们在内容快速加载时等待很长时间)

1 个答案:

答案 0 :(得分:0)

答案很简单,只需使用Google Maps事件处理程序api即可。在我的测试中,它按此顺序触发bounds_changed,然后tilesloaded,最后idle。所以我只是设置一个标志,以便稍后检查idle事件,它完美无缺。

      // this callback runs when the mapobject is created and rendered (because bound_changed fires at initialization), only fire it once to prevent unnecessary callbacks during panning/zooming
      google.maps.event.addListenerOnce(map, 'bounds_changed', function () {
         // do something only the first time the map is loaded
         console.log("Google Maps event: bounds_changed");
      });

      // this callback runs when the mapobject is shown for the first time and all tiles are loaded
      google.maps.event.addListener(map, 'tilesloaded', function () {
         console.log("Google Maps event: tilesloaded");
      });

      // this callback runs when the mapobject is fully created and rendered and the map is completely idle
      google.maps.event.addListener(map, 'idle', function () {
         // do something only the first time the map is loaded
         console.log("Google Maps event: idle");
         mapReadyToPrint = true;
         console.log("mapReadyToPrint:", mapReadyToPrint);
      });