Skip to content

Instantly share code, notes, and snippets.

@gerardpaapu
Created September 17, 2012 22:03
Show Gist options
  • Save gerardpaapu/3740060 to your computer and use it in GitHub Desktop.
Save gerardpaapu/3740060 to your computer and use it in GitHub Desktop.

This snippet illustrates how you can allow your users to put your library into whatever global they see fit.

This technique currently relies on your script tag being the last on the page at time of execution. This means that it will not probably not play nicely with async or defer

<!doctype html>
<script src="lib.js" data-path="MY.LIBRARY" ></script>
<script>
MY.LIBRARY.greet('Michael');
</script>
(function () {
function defineWithPath(path, obj) {
var root = window;
var components = path.split('.');
var len = components.length;
var i, component;
for (i = 0; i < len - 1; i++) {
component = components[i];
root = root[component] || (root[component] = {});
}
var last = components[components.length - 1];
root[last] = obj;
}
function getPath() {
var scripts = document.getElementsByTagName('script');
var us = scripts[scripts.length - 1];
return us.getAttribute('data-path') || null;
}
var path = getPath() || 'DEFAULT';
defineWithPath(path, {
greet: function (name) {
console.log('Hello, ' + (name || 'World') + '.');
}
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment