The <iframe> element has a somewhat convoluted history: introduced by Microsoft and supported in early versions of Internet Explorer, it was incorporated into HTML 4.0, banished from XHTML, and reintroduced in HTML5.

An <iframe> is easiest to understand as a window onto another document or site: the element’s purpose is to place content from one HTML document in the context of another. This takes place quite literally: when you add an <iframe> to a page, you are looking through a window from that page into another site, with full interactivity within that space. This is why Google Maps and YouTube promote users to embed their content by using an <iframe> element: rather than hosting any portion of the complex web app yourself, your page simply views the web service through an integrated window.

As a simple example, to open the front page of Metafilter in an <iframe>, you’d use the following code:

<iframe style="width: 20%; height:300px" src="http://metafilter.com"></iframe>

…which provides the result that you see above. Note that many services, including YouTube, will create far more code for iframes than is necessary, but the only requirement is the src attribute together with a width and height.

iframe security concerns

Just like an open window in your house, iframes constitute a security concern: as your page communicates with the site within the <iframe>, it can communicate with yours, potentially allowing intrusion into your site.

HTML5 introduces the sandbox attribute, which prevents the framed site from execution of or access to any of the following:

  • plugins
  • form submission
  • scripts (including JavaScript)
  • links outside of the frame
  • access to cookies, local storage, and other pages on the originating domain

sandbox is supported in all modern browsers (IE10, Firefox 17+, Chrome 22+ and Safari 5.1+) with the exception of Opera, making it easy to prevent malicious attacks: <iframe seamless sandbox src=http://distrusted.com></iframe>

Possible iframe performance issues

Using an <iframe> in your site means that you are running at least two pages in one: the originating page plus the content of the <iframe>. This often doubles or triples the total size of your page. Issues of performance inevitably arise: one recommendation would be to turn off iframes as the viewport narrows, as smaller screens are associated with mobile devices.

Conclusion

With all of these conditions and limitations, what practical purpose do iframes have? Advertising is one obvious possibility: most ads are delivered in fixed dimensions from a central server, making heavy use of iframes in the destination page. As we’ll see in an upcoming article, the element has far more artistic promotional purposes: it is singularly suited for taking live screenshots of other sites, making frames very useful for creating portfolio pages.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.