end video

This lesson is only accessible in the paid version of the course.

Get access to all lessons 💫 price: 34.99$

If you already have an account click here.

Do you speak JavaScript?

§ Call-to-action widgets script tag replacement

Did you ever wonder how the call-to-action widgets work? You know, those little buttons for sharing content on social networks. In this lesson we'll see how.

The widgets are often 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 is a script tag, how does it know where to inject the button? The goal of this chapter is to give you an answer to this question.

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>

We want to see is a link followed by "Content here" followed by another link. We not only want to replace those script tags, but we want different results for each one of them. The color of the button should be different.

I was surprised to find out that the code behind widget.js could be quite short. Just eight 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 are used are document.currentScript and element.dataset. The first one gives us access to the element whose script we are currently processing. The dataset property is quick access to the data attributes of the element.

\newpage

The snippet above creates a new div and injects in it a link. Then, using replaceChild 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>
discussion

Materials

Materials related to the lesson:
Files associated with the lesson

Materials

Next: Client side routing(08:19)

To the lesson →