sunflower seed
sunflower seed

Reputation: 303

How to add(embed) a widget to another website like tawk.to, disqus etc.?

I am trying to make a widget that I can add to another website through code embedding, much like tawk.to.

I have tried using iframe and object with embed but for some reason it is slow. As a page it fetches the images fast but when I embed it, it is slow. Also I heard that it is not best practice.

So I searched what other websites are doing and I found out that disqus is using iframe and tawk is using the below code. As messaging widget don't use much data, iframe seems to work but in my case, my widget is fetching a lot of data from an API.

tawk.to is using this code:

<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/APIKEY';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->

I already have a page and I want to put in inside another website page using something? And it is gonna display a small icon like tawk.to and when clicked it's gonna show the page inside the widget.

How can I achieve this?

Upvotes: 2

Views: 2076

Answers (1)

Macros
Macros

Reputation: 7119

Using an iframe as in itself is not slow however if you insert the iframe directly then it will load inline with the rest of the page. The approach that Tawk.to use is:

  1. Simple javascript (as you have already pasted), which simply creates a second script element within the page, explicitly sets it to async, and then adds it to the DOM - this then triggers the script to load.

  2. This script will then call the Tawk servers, and return a more complete javascript, containing their full code, but without slowing the page load down.

  3. In the case of Tawk.to they do use an iframe to display their chat widget - which is generally a straightforward way of ensuring there are no styling clashes, or if wanting to load a remote page directly.

I have created widgets both in this way, and also by adding elements directly to the DOM. The key part here is the js chaining - the first script does nothing except construct the second and doesn't impact page load.

Applying this to your case, you could:

  1. Use similar JS chaining to load your main JS script

  2. Have the main JS script add a hidden iframe which loads the page you already have.

  3. Add a button element to the DOM which toggles the visibility of the iframe you added.

Upvotes: 1

Related Questions