Creating Awesome Embeddable Scripts

I was looking at a video about the new version of Apple's MapKit JS, their web maps library, and they showed how to initialise the SDK by loading the script.

The code looks something like this:

    crossorigin async
    data-token="Your MapKit JS token"></script>

That's very neat, being able to specify the token and other details using the data- attributes on the script tag. That made me wonder how this worked.

After searching through the minified version of the source code for a bit, I found out what their method was for making this work: document.currentScript

I did not know that property existed - but apparently it's supported in all major browsers and allows you to get the script DOM element that invoked the currently running Javascript.

Now that we know that, we could build a similar embed script ourselves, combining currentScript with the dataset API for getting HTML data attributes.

Here's our example HTML:

   data-message="Hello world"

And our embed.js script:

if (document.currentScript) {
   // Invoked from an HTML page
   const data = document.currentScript.dataset;
   if (data.message) {
      alert(`Embed script says: ${data.message}`);

Hopefully you can use this the next time you are building an embed system.

I really enjoy building these things, and have gotten the opportunity to build a few of them: