Skip to content

Instantly share code, notes, and snippets.

@nbhartiya
Created March 25, 2015 22:03
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nbhartiya/7aadca9e98ddbc0850d2 to your computer and use it in GitHub Desktop.
Save nbhartiya/7aadca9e98ddbc0850d2 to your computer and use it in GitHub Desktop.
Javascript Widget Embedder Script
<script data-version='v1' data-client-id='clients-id' id='unique-embedder-id' type='text/javascript'>
// "data-version": It's useful to put the version of your embedder script in the "version" data
// attribute. This will enable you to more easily debug if any issues arise.
// "data-client-id": This id allows us to pull up the correct client's settings from our database.
// Each client may have different settings associated with their widget, and you can load them
// with this!
// "id": This HTML id allows us to refer to this embedder script's location. This is helpful
// if you want to inject html code in specific places in hour hosts's website or if you want to
// insert your payload script right next to this in the <head> tag.
// We wrap our code in an anonymous function to prevent any of our variables from leaking out
// into the host's site.
(function() {
function async_load(){
//We begin to construct the payload script that we will shortly inject into our client's DOM.
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
// Below is the URL you want them to get your payload script from!
// You may even want to put your payload script in Amazon S3 and have it be independent
// of your web server.
var theUrl = 'http://www.your-website.com/assets/your-payload-script.js';
// At the end we tack on the referrer's URL so we know which website the request is coming from.
s.src = theUrl + ( theUrl.indexOf("?") >= 0 ? "&" : "?") + 'ref=' +
encodeURIComponent(window.location.href);
// This finds the location of our embedder script by finding the element by it's Id.
// See why it was useful to give it a unique id?
var embedder = document.getElementById('unique-embedder-id');
// This inserts our payload script into the DOM of the client's website,
// just before our embedder script.
embedder.parentNode.insertBefore(s, embedder);
}
// We want the our embedder to do its thing (run async_load and inject our payload script)
// only after our client's website is fully loaded (see above).
// Hence, we wait for onload event trigger. We attachEvent because we don't want to
// replace our client's current onLoad function with ours (they might be doing a bunch
// of things on onLoad as well!)
if (window.attachEvent)
window.attachEvent('onload', async_load);
else
window.addEventListener('load', async_load, false);
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment