Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

Here is how call-to-action widgets probably work

Here is how call-to-action widgets probably work Photo by Cristian Escobar

Did you ever wondered how the call-to-action widgets work? You know, those little buttons for sharing content in the social networks. Very often they are distributed as iframes but sometimes we have to copy/paste script tags. And the instructions are "Place the following code where you want the button to appear". But if that's a script tag how it knows where to inject the button? The goal of this article is to give you an answer on this question.

So, let's start with the markup below:

<script src="./widget.js" data-color="#ff0000"></script>
<section>
  Content here.
</section>
<script src="./widget.js" data-color="#00ff00"></script>

What we want to see is a link followed by "Content here." followed by another link. Notice that we not only want these script tags replaced but we are also passing some settings (the desired color of the button).

I was surprised to find out that the code behind widget.js could be quite short. Just 8 lines:

(async function loadContent() {
  const options = document.currentScript.dataset;
  const node = document.createElement('div');
  const style = options.color ? `color:${options.color}` : '';
  
  node.innerHTML = `<a href="http://mysite.com" style="${style}">click me</a>`;
  document.currentScript.parentNode.replaceChild(node, document.currentScript);
})();

The APIs that I wasn't aware of are document.currentScript and element.dataset. The first one gives us access to the element whose script is currently being processed. The dataset property is a quick access to the data attributes of the element. So far I was happily using getAttribute.

The snippet above creates a new div and injects in it a link. Then by using replaceChild it swaps the script tag with that newly created element. The result is:

<div><a href="http://mysite.com" style="color:#ff0000">click me</a></div>
<section>
  Content here.
</section>
<div><a href="http://mysite.com" style="color:#00ff00">click me</a></div>
If you enjoy this post, share it on Twitter, Facebook or LinkedIn.