简体   繁体   English

如何检查iframe是否已在JavaScript中加载

[英]How to check iframe is loaded in JavaScript

I am loading in an iframe which takes some time to load. 我正在iframe中加载,加载需要一些时间。 I need to check that the iframe has loaded completely and get the height of it 我需要检查iframe是否已完全加载并获取其高度

Can anybody tell how to how to check iframe is loaded in JavaScript? 谁能告诉我如何检查JavaScript是否已加载iframe?

You can use jQuery's load method to load iFrame and then in the callback get the contents of that. 您可以使用jQuery的load方法加载iFrame,然后在回调中获取该内容。 And depending on the content of the iFrame you can make further decision. 根据iFrame的内容,您可以做出进一步的决定。

$('#iFrame').load(cbLoaded);

function cbLoaded()
{
   var doc = $('#iFrame').contents()[0].documentElement;
   // Get contents here:
   var content = doc.innerText || doc.textContent;
}

In JavaScript, the script , img , and iframe tags all support a load event. 在JavaScript中, scriptimgiframe标签均支持load事件。

You can leverage it in vanilla JS, which is already answered , with either: 您可以在已经回答过的vanilla JS中利用以下任一方法:

document.getElementById('#my-iframe').addEventListener('load', function () { ... });

document.getElementById('#my-iframe').onLoad = function() { ... };

But if you need an example of how to implement this in Angular specifically, you can do so in the controller or inside a directive's link function by using the element argument. 但是,如果您需要一个具体如何在Angular中实现此功能的示例,则可以在控制器中或在指令的链接函数中使用element参数来实现。

In a controller: 在控制器中:

myApp.controller('SomeController', ['$scope', function($scope) {
  var iframe = angular.element('#my-iframe');
  iframe.on('load', function() {
    console.log(iframe.height());
  });
}]);

In a directive: 在指令中:

myApp.controller('SomeController', ['$scope', function($scope) {
  $scope.foo = 'bar';
}])
.directive('myDirective', ['$interval', function($interval) {
  function link(scope, element, attrs) {
    var iframe = element.find('#my-iframe');
    iframe.on('load', function() {
      $interval(function() {
        console.log(iframe.height();
      }, 1000);
    });
  }

  return {
    link: link
  };
}]);

In javascript you may listen on DOMContentLoaded , the jQuery equivalent of document ready, and so add the event listener onload to the iframe: 在javascript中,您可以监听DOMContentLoaded ,它相当于jQuery就绪的jQuery,因此将事件监听器onload添加到iframe:

 document.addEventListener("DOMContentLoaded", function(e) { document.getElementById('ifrm').addEventListener('load', function(e) { document.body.innerHTML += '<p>Iframe loaded</p>'; }, false); }); 
 <iframe id='ifrm' src="https://www.wikipedia.org/"></iframe> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM