iframe vs innerHTML for a modal dialog - which is

2019-05-30 15:25发布

问题:

I am emulating a modal window functionality on my HTML5 page by creating a div with position: fixed, centered in the browser window etc. In some cases my modal window just shows a message with one or more buttons, such as OK Cancel, but in other cases I'm showing more complicated forms, e.g. an instant messaging dialog.

The question is for the more complicated cases. So which is better, (1) to have an <iframe> in my "modal" window or (2) a <div> plus some Ajax code that retrieves the contents of my form and injects it into the div's innerHTML?

What are some caveats in either case? When you choose one over the other, what is your reasoning?

Browser requirements: IE9+ and the rest of the sane browsers.

回答1:

You should only use an iframe if you actually need an iframe. Reasons to use an iframe are:

  1. The simplest way to load content from another domain.
  2. To isolate the security context for content from a separate domain.
  3. To embed a completely independent web page (independent scripts, independent style sheets, etc...) in your web page.
  4. You don't want to write ajax code to load content dynamically and want to just use the built-in .src capability of an iframe.

If you don't need any of these capabilities of an iframe, then it's generally easier to use use a div (which will auto-size to its content - whereas an iframe will not) and put the desired content in that div.

Either can be made to work.