How do hosted services like UserVoice embed their content on other web sites?

浪子不回头ぞ 提交于 2019-12-04 20:37:07

Here is a great tutorial I found on How to build a web widget (using jQuery)

Generally, what you are describing is called a "Javascript Widget" (UserVoice's just happens to show up on the side of the page).

There is a good tutorial about creating Javascript Widgets that you can check out.

The basic structure of such an embeddable service would be:

  1. If the service doesn't mandate that the script is to be included at the bottom of the page, hook the body onload event, without stepping on the toes of any existing handlers (by intercepting the existing handler function, which could in turn be chained to other functions).
  2. Inject new HTML elements into the document. The HTML code would most likely be inlined into the script as string literals as setting innerHTML on a single injected element would be easier and faster than direct DOM manipulation using a flurry of function calls.
  3. The entire script should live inside a closure to avoid name clashes.
  4. A JS framework may or may not be used; caution is required when including a framework since it could clash with a pre-existing, different framework, or a different version of the same framework.

EDT: Generally you'll make your client/customer/friend include a script in their page, then via that script you can do following:

In pure JS you can load scripts from remote location (or not so remote) dynamically via

   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = 'your/remote/scripts/path.js';
   document.getElementsByTagName('body')[0].appendChild(script);

// $.getScript('your/remote/scripts/path.js'); in jquery but you'll be sure jQuery loaded on remote site

Then script you loaded can perform different actions like creating elements like this

var body = document.getElementsByTagName('body')[0]; var aDiv = document.createElement('script'); /* here you can modify your divs properties and look */ body.appendChild(aDiv); // $('').appendTo('body'); for jQuery

For deeper look into JavaScript you can read for example Javascript: The Good Parts or Definitive Guide To Javascript.

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