jQuery 检查元素是否已加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45282649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:25:16  来源:igfitidea点击:

Check if element is loaded

jqueryeventsdomloading

提问by Florian Müller

I have a site and an iFrame in that site, as well as a lot of other content (images and so on).

我有一个站点和该站点中的 iFrame,以及许多其他内容(图像等)。

Now I'm using jQuery's $(document).ready(function() { ... });to execute code. In that code, I'm trying to manipulate content in the iFrame. However, I have to assure the iFrame is loaded to execute the code.

现在我使用 jQuery$(document).ready(function() { ... });来执行代码。在该代码中,我试图操作 iFrame 中的内容。但是,我必须确保加载 iFrame 才能执行代码。

The iFrame usually loads in exactly the same time when the code is executed, so it sometimes fails and sometimes not.

iFrame 通常在代码执行的同时加载,所以它有时会失败,有时不会。

If I use $('#iframe').load(function(){ });, the event is not always executed, because at that moment I attach that load listener, the iFrame may be already finished with loading, and the load event won't get executed again. If I leave it away, the elements are sometimes not yet there (the code get's executed too early).

如果我使用$('#iframe').load(function(){ });,该事件并不总是执行,因为在那一刻我附加了加载侦听器,iFrame 可能已经完成加载,并且加载事件不会再次执行。如果我不理会它,元素有时还不存在(代码执行得太早)。

So what I want to achieve is something like that:

所以我想要实现的是这样的:

if iFrame is already loaded
  -- execute code 
else 
  -- $('#iframe').load(function() {?/*execute code*/ });

Is there a better way to achieve this without using a dirty timeout? Or if using this approach, is there a function which checks if the element is already loaded or not?

有没有更好的方法可以在不使用脏超时的情况下实现这一目标?或者如果使用这种方法,是否有一个函数可以检查元素是否已经加载?

采纳答案by Roamer-1888

Make sure that $('#iframe').load(function(){ });is executed before the iFrame's srcis set.

确保$('#iframe').load(function(){ });在设置 iFrame 之前执行src

To achieve this, set the srcfrom javascript, not in HTML.

要实现这一点,请设置src来自 javascript,而不是在 HTML 中。

Also, loading sequence matters here. If your jQuery's overall wrapper is jQuery(window).load(function() {...}), the behaviour will be different from that given by jQuery(function() {...}).

此外,加载顺序在这里很重要。如果您的 jQuery 的整体包装器是jQuery(window).load(function() {...}),则行为将与jQuery(function() {...}).

回答by A. Wolff

For same domain iframe (as it seems to be your case here):

对于同一个域 iframe(因为这里似乎是你的情况):

You can check if iframe has some content and then trigger load event using following logic:

您可以检查 iframe 是否有一些内容,然后使用以下逻辑触发加载事件:

$('#iframe').one('load', function(){
  console.log("Sure load event is called!")
}).each(function(){
  if(this.contentDocument.body.children.length) {
    $(this).trigger('load');
  }
})

For handling cross domain iframe too:

也用于处理跨域 iframe:

Your best bet i guess and if you don't need to support IE8 is probably to capture loadevent and set it before you set iframein DOM, by calling it e.g inside headsection:

我猜你最好的选择,如果你不需要支持 IE8 可能是捕获load事件并在你iframe在 DOM 中设置之前设置它,通过调用它例如在内部head部分:

document.addEventListener(
    'load',
    function(event){
        var elm = event.target;
        if( elm.id === 'iframe'){ // or any other filtering condition
            console.log("Sure iframe is loaded!")
        }
    },
    true // Capture event
);

回答by Eric Farias

The DOM always becomes ready before the page is fully loaded, it is usually not safe to attach a load event listener in code executed during a .ready() handler. For example, scripts can be loaded dynamically long after the page has loaded using methods such as $.getScript(). Although handlers added by .ready() will always be executed in a dynamically loaded script, the window's load event has already occurred and those listeners will never run.

DOM 总是在页面完全加载之前准备好,在 .ready() 处理程序期间执行的代码中附加加载事件侦听器通常是不安全的。例如,可以使用 $.getScript() 等方法在页面加载后很长时间内动态加载脚本。尽管 .ready() 添加的处理程序将始终在动态加载的脚本中执行,但窗口的加载事件已经发生并且这些侦听器永远不会运行。

jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:

jQuery 提供了多种方法来附加将在 DOM 准备就绪时运行的函数。以下所有语法都是等效的:

  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )
  • $( 处理程序 )
  • $( 文档 ).ready( 处理程序 )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( 处理程序)
  • $().ready( 处理程序 )

load () documentation, read () documentation

加载()文档阅读()文档