Creating an Embeddable Javascript Widget

One of the updates I’m working on for WhichBeach is the ability for other website owners to embed WhichBeach widgets that will display up-to-date beach data. This is very much a work in progress, but I’d like to share.

I’ve never done anything like this before, so I thought I’d start by taking some inspiration from Facebook’s Like Button implementation:

<!-- Load Facebook SDK for JavaScript -->
	<div id="fb-root"></div>
	<script>(function(d, s, id) {
	  var js, fjs = d.getElementsByTagName(s)[0];
	  if (d.getElementById(id)) return;
	  js = d.createElement(s); js.id = id;
	  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1";
	  fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));</script>

	<!-- Your like button code -->
	<div class="fb-like" 
		data-href="http://www.your-domain.com/your-page.html" 
		data-layout="standard" 
		data-action="like" 
		data-show-faces="true">
	</div>

To break it down, Facebook’s script injects a new script tag that pulls in their Javascript SDK. They’re also ensuring that the script is only injected once into the page.

I think I can make this work for me too:

<!-- Load WhichBeach SDK for Javascript -->
<div id="wb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//whichbeach.app/js/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'whichbeach-jswidget'));</script>

<div class="wb-widget" data-size="skyscraper"></div>

Great. Now all that’s left is to write a Javascript SDK! I’ll need to expose that on /js/sdk.js and add all my widget logic in there.

In due time… if anyone has any tips and resources that they think I should be using – let me know in the comments!

5 comments

  1. Hello, when you say “All that’s left is to write a JS SDK!”, how to know what to write there? Do you have any follow up on the topic? 🙂

  2. Dude… this article is like telling me you’re gonna build a house, showing me a picture of the house, and then saying “Hey you only have to build it now!”. You need to improve this article immensely. I feel robbed of my time. *grumble*

  3. Thanks for the article. It’s great, but I’m curious how did you end up setting up the development of sdk.js?

    Do you have a Webpack build or something similar?

    Thanks for discussing this.

    Cheers

Leave a comment

Your email address will not be published.