Javascript:在页面加载后添加iframe元素 [英] Javascript: add iframe element after page has loaded

查看:112
本文介绍了Javascript:在页面加载后添加iframe元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Javascript我需要找到添加iframe元素的最佳方法:

Using Javascript I need to find the best way to add a iframe element that is:


  1. 完全对用户隐藏。

  2. 在页面完全加载后创建。 ie应该对用户完全不显眼,不会以任何方式影响图像和其他脚本等的加载。


推荐答案

你可以像这样添加一个隐藏的 iframe

You can add a hidden iframe like this:

var iframe = document.createElement('iframe');
iframe.style.display = "none";
iframe.src = /* your URL here */;
document.body.appendChild(iframe);

如果你需要在页面加载时这样做,你可以简单地将相关代码放在脚本标签中在文档的末尾,或通过窗口 加载事件(窗口)将其挂钩。 onload = yourFunction; ),虽然窗口 加载事件发生在页面的后期加载过程。当然,就像浏览器上涉及JavaScript的许多内容一样,如果你使用像 Prototype , jQuery 关闭,或任何其他人,因为这些可以消除浏览器差异。 (也就是说,上面的代码适用于我熟悉的任何浏览器。)一旦页面加载,库通常会提供一种处理方式,但早于窗口 加载通常会发生。 jQuery提供 ready 函数; Prototype提供 dom:loaded 事件;等等。

If you need to do that on page load, you can simply put the relevant code in a script tag at the end of your document, or hook it up via window load event (window.onload = yourFunction;), although the window load event happens quite late in the page load process. And of course, like many things involving JavaScript on browsers, you may find your life is a bit easier if you use a library like Prototype, jQuery, Closure, or any of several others, as these can smooth out browser differences. (That said, the above code will work on any browser I'm familiar with.) Libraries will typically offer a way of doing things as soon as the page is loaded, but earlier than window load typically happens. jQuery provides the ready function; Prototype provides the dom:loaded event; etc.

例如,如果你将它放在 body 标签的末尾,它将创建iframe在所有其他已加载(包括所有图像,窗口 加载之后才开始已加载所有图片):

For instance, if you put this at the end of your body tag, it will create the iframe after everything else has loaded (including all images, window load doesn't fire until all images have loaded):

<script type='text/javascript'>
window.onload = function() {
    var iframe = document.createElement('iframe');
    iframe.style.display = "none";
    iframe.src = /* your URL here */;
    document.body.appendChild(iframe);
};
</script>

这篇关于Javascript:在页面加载后添加iframe元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆