Iframe v/s external js (to show my website's content on other websites)

折月煮酒 提交于 2019-12-12 05:44:27

问题


In my project,

I have created a code snippet which can be copied and then put in any website. It shows my content on other websites.

What I am using now is :

<script type='text/javascript'>
var user = 'abc';
var age = '23';

document.write('<iframe src="http://www.mysite.com/page.php?user='+ user + '&age=' + age + '" ></iframe');
</script>

In page.php,

I do some processing based on user and age and show dynamic content.

My approach works fine.

But when I look into some good standard ways to do such tasks, I find a different way.

Take an example of google adsense code.

<script type='text/javascript'>
 var a = 'somedata';
 var b = 'someotherdata';
</script>

<script type='text/javascript' src='http://www.google.com/adsenseurl.js'></script>

I guess, since a and b are global; adsenseurl.js must be using it and may be finally they are showing it on iframe.

So, now the question.

What's the advantage in using google's approach and whats wrong in my approach ?

p.s. I know I should try to avoid using iframes but I dont see any other way to accomplish this.


回答1:


The main difference between your approach and adSense is in my opinion that your code has to be placed where the ads have to appear and loading a script like adsense, they can place the iframe in the DOM after examining the page - using

var myIframe = document.createElement('iframe');
.
.
someDOMObject.appendChild(myIframe);

and/or manipulating the zindex to float the iframe above the page

Lastly the iFrame is useful (regardless of "oh noes - iframes are evil" you may hear) since you can use any css and jquery you like. If the page you are on already has styled divs and old versions of jQuery you will have a lot more work to make it look like you want.




回答2:


Why use an iframe? If your user loads the <script src='yoursite.com/something.js'></script>, you immediately have access to his DOM and you can do whatever you want via that something.js. In the same way that you load jQuery from some CDN - it can be immediately used to modify the DOM.

Otherwise there's really no difference except that:

  1. Instead of embedding a potentially big amount of code that your user has to maintain, he just provides the necessary variables and simply links to a script on your page.
  2. You can update the js code on your server and make sure that all your users are immediately (minus caching) up-to-date with the new functionality.

There might be other advantages, but these two should suffice I believe.



来源:https://stackoverflow.com/questions/10032696/iframe-v-s-external-js-to-show-my-websites-content-on-other-websites

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!