设置iFrame源并使用jQuery重新加载

时间:2015-09-02 22:21:11

标签: javascript jquery iframe reload jquery-deferred

我有一个独特的问题 - 虽然我看到过类似的问题和答案 - 但没有一个能够解决我的挑战。

目前,我提供了一个“打印”按钮,可以根据嵌入和隐藏的iframe在浏览器上加载打印对话框。这很好用,但我不想通过拉入大型PDF的iframe来减慢页面加载速度。

所以,我想在没有源代码的情况下加载iframe,然后在用户点击打印图标时编写正确的源URL,然后重新加载iframe,最后显示对话框。

不幸的是,在重新加载iframe之前弹出打印对话框,因此在对话框中加载空白页面。在随后的点击中,PDF已加载并准备打印。

<a href='#' id='load_pdf' ><i class='fa fa-2 fa-print'></i></a>
<iframe id="iFramePdf" src="" style="display:none;"></iframe>

<script type="text/javascript">
  jQuery(document).ready(function() {
    $("#load_pdf").click(loadPDF);

    function loadPDF() {
      $('#iFramePdf').attr('src', "my.pdf");
      // Attempt to reload iframe
      $('#iFramePdf').load("my.pdf");
      sendPrint('iFramePdf')
    }

    function sendPrint(elementId) {
      var iframe = $(element_id)[0]; 
      iframe.contentWindow.focus(); 
      iframe.contentWindow.print();
    }

});
</script>    

我尝试了以下各种方法重新加载:

// Attempt 1
$('#iFramePdf').attr('src', function () { return     
$(this).contents().get(0).location.href });

// Attempt 2
$('#iFramePdf').attr("src", $('#iFramePdf').attr("src"));
$('#iFramePdf').attr('src', function () { return $(this).contents().get(0).location.href });

// Attempt 3
$('#iFramePdf')[0].contentWindow.location.reload(true);

// Attempt 4
var getMyFrame = document.getElementById(elementId);
getMyFrame.contentWindow.location.reload(true);

我甚至尝试过使用jQuery的延迟方法,但没有运气(可能是因为我缺乏知识)。如果我能得到任何指导,我会很感激。

2 个答案:

答案 0 :(得分:1)

尝试改变这个:

function loadPDF() {
  $('#iFramePdf').attr('src', "my.pdf");
  // Attempt to reload iframe
  $('#iFramePdf').load("my.pdf");
  sendPrint('iFramePdf')
}

这样的事情:

function loadPDF() {
  $('#iFramePdf').attr('src', "my.pdf");
}

  $('#iFramePdf').load(function(){
  sendPrint('iFramePdf')
})

它应该有用

答案 1 :(得分:0)

您可以尝试.promise()。出于显而易见的原因,我无法对其进行测试,但我认为3秒应足以让iframe加载。请注意,这在语法上是正确的,因为我可以在不进行测试的情况下获得它。相应地调整fadeIn(1800)delay(1200)

<强> HTML

<a href='#' id='load_pdf' ><i class='fa fa-2 fa-print'></i></a>
<p id="msg" style="display: none;">Printing Document...</p>
<div id="printPort" style="opacity: 0; width: 1px; height: 1px;"></div>

<强>的jQuery

   $(function() {

        $("#load_pdf").on('click', loadPDF('my.pdf'));

        // Create the iframe, and put it inside #printPort
        // Change it's src to the file argument
        // Animate the #msg for 3 seconds

        var loadPDF = function(file) {
          $('<iframe id="iFramePdf" src="blank.html"></iframe>').appendTo("#printPort");
          $("#iFramePdf").att('src', file);
          return $('#msg').fadeIn(1800).delay(1200).fadeOut();
        }

        var sendPrint = function(elementId) {
          var iframe = $(element_id)[0]; 
          iframe.contentWindow.focus(); 
          iframe.contentWindow.print();
        }

        // Once the animation is done the promise will resolve and sendPrint will execute on callback.

        $.when(loadPDF).done(sendPrint('iFramePdf'));
    });
相关问题