简体   繁体   中英

Load External Cross Domain HTML Content in iFrame vs. from Asynchronously JavaScript?

I have an HTML widget, ie, HTML Content that can be included in other pages. So lets say my content is from domain A and a page in domain B includes the widget from domain A. I see two ways to include the cross domain content in a page of domain B.

Note: The widget will show some diagrams, ie, data visualisation.

Variante 1:

Using an iFrame.

<iframe src="domain_A_url_to_widget" width="200" height="400" name="foreignWidget">
  <p>no Browser support</p>
</iframe>

Variante 2:

Using asynchronously JavaScript.

<script type="text/javascript">
  (function(d){
    var f = d.getElementsByTagName('SCRIPT')[0],
        p = d.createElement('SCRIPT');
    p.type = 'text/javascript';
    p.async = true;
    p.src = '//domainA.com/js/widget.js';
    f.parentNode.insertBefore(p, f);
  })(document);
</script>

1. What are the advantages and disadvantages of both variants?

2. Is there any possibility to use JQuery and CSS in variant 2?

3. Can the user interact with my widget in both variants event if the widget loads content with ajax?

The main difference is that the contents of an iframe are effectively their own page, whereas if you pull in some HTML via JavaScript it will become part of the DOM of the original page. As you're calling it a "widget", I'd guess that this is sort of a component of the original page you want to add in, so option 2 is the better one in my opinion - this isn't really what iframe is meant for.

An iframe creates a sandboxed environment.

Benefit: no risk of conflict with the main page (for example styles).

Downside: because of cross-domain limitations, it is very difficult for the content of the iframe to interact with the main page.

Examples:

  • option 1 is fine for ads, or for a weather widget
  • option 2 will be easier for a widget that highlights keywords on the main page.

You can of course use jQuery in variant 2 (remember: jQuery is just a bunch of JavaScript code). You can use css too, you'll load it via a link or style tag (the same way you loaded your script via a script tag).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM