Iframe问题需减少页面加载时间

11
我有一个网站(WordPress),上面有几千篇文章。一篇文章的样子是这样的:

...

[tab:source1]
<iframe width="560" height="315" src="https://www.youtube.com/embed/U3rKPexoEcA" frameborder="0" allowfullscreen></iframe>
[tab:source2]
<iframe src="https://player.vimeo.com/video/60718161?title=0&byline=0&portrait=0&badge=0" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<p><a href="https://vimeo.com/60718161">HOW TO SHARPEN PENCILS</a> from <a href="https://vimeo.com/pricefilms">Pricefilms</a> on <a href="https://vimeo.com">Vimeo</a>.</p>
[tab:source3]
<iframe width="640" height="360" src="http://www.worldstarhiphop.com/embed/100588" frameborder="0" allowfullscreen></iframe>

我的页面加载时间有时会超过两位数。我知道这是为什么,但不确定该如何解决。我想用以下方法之一来解决:

Iframe setTimeout()

或者: 看起来像这样的动态异步iframe:

<script>
(function(d){
  var iframe = d.body.appendChild(d.createElement('iframe')),
  doc = iframe.contentWindow.document;

  // style the iframe with some CSS
  iframe.style.cssText = "position:absolute;width:200px;height:100px;left:0px;";

  doc.open().write('<body onload="' + 
  'var d = document;d.getElementsByTagName(\'head\')[0].' + 
  'appendChild(d.createElement(\'script\')).src' + 
  '=\'\/path\/to\/file\'">');

  doc.close(); //iframe onload event happens

  })(document);
</script>

用任一种方法,我该如何将此应用于整个网站上的所有 iframe?我认为不可能单独更改每个 iframe。

1个回答

1
在输出之前,我建议你使用正则表达式替换php模板中的所有iframe标签为你所需的加载解决方案。例如:<iframe.*src="([^"]*)".*\/iframe>。我认为将iframes替换为包含加载gif和data-src属性的div,并将真实的iframe url作为子元素是一个好的解决方案。然后,在页面加载后使用js加载div内的iframes。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接