且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 HTML5 替代 iFrame

更新时间:2023-01-03 16:31:14

基本上有 4 种方法可以将 HTML 嵌入网页:

Basically there are 4 ways to embed HTML into a web page:

  • iframe 的内容与您的页面完全不同.虽然这主要是一个很棒的功能,并且它在浏览器版本中是最兼容的,但它带来了额外的挑战(将框架的大小缩小到其内容是很困难的,脚本输入/输出非常令人沮丧,几乎不可能设置样式).莉>
  • AJAX.正如此处显示的解决方案所证明的那样,您可以使用 XMLHttpRequest 对象来检索数据并将其注入您的页面.它并不理想,因为它依赖于脚本技术,从而使执行速度更慢且更复杂,其中包括 缺点.
  • 黑客.这个问题中提到的很少,也不是很可靠.
  • HTML5 网络组件.HTML 导入是 Web 组件的一部分,允许将 HTML 文档捆绑在其他 HTML 文档中.这包括 HTMLCSSJavaScript.html 文件可以包含的任何其他内容.这使其成为具有许多有趣用例的绝佳解决方案:将应用拆分为捆绑组件,您可以将这些组件作为构建块分发,更好地管理依赖项以避免冗余、代码组织等.这是一个简单的示例:

  • <iframe> An iframe's content lives entirely in a separate context than your page. While that's mostly a great feature and it's the most compatible among browser versions, it creates additional challenges (shrink wrapping the size of the frame to its content is tough, insanely frustrating to script into/out of, nearly impossible to style).
  • AJAX. As the solutions shown here prove, you can use the XMLHttpRequest object to retrieve data and inject it to your page. It is not ideal because it depends on scripting techniques, thus making the execution slower and more complex, among other drawbacks.
  • Hacks. Few mentioned in this question and not very reliable.
  • HTML5 Web Components. HTML Imports, part of the Web Components, allows to bundle HTML documents in other HTML documents. That includes HTML, CSS, JavaScript or anything else an .html file can contain. This makes it a great solution with many interesting use cases: split an app into bundled components that you can distribute as building blocks, better manage dependencies to avoid redundancy, code organization, etc. Here is a trivial example:

<!-- Resources on other origins must be CORS-enabled. -->
<link rel="import" href="http://example.com/elements.html">

本机兼容性 仍然是一个问题,但您可以使用 polyfill 使其在 常青浏览器今天.

Native compatibility is still an issue, but you can use a polyfill to make it work in evergreen browsers Today.

您可以在此处这里.