Skip to content

Instantly share code, notes, and snippets.

@kentbrew

kentbrew/mypage.html

Created Feb 17, 2010
Embed
What would you like to do?
Evolving a JavaScript Widget
<!doctype html>
<html>
<head>
<title>My Javascript Widget</title>
</head>
<body>
<script src="widget.js"></script>
</body>
</html>
// the evolution of a widget
// coded by Kent Brewster
// http://kentbrewster.com
// bare minimum primordial widget
// - find the SCRIPT tag that called you
// - create a DIV placeholder
// - delete your calling SCRIPT tag
(function (d, w) {
// localVar $ = window[someRandomThing] = an empty object
// there are lots of ways to make random names; this one is simple
// and feeds my vanity a bit by using my initials :)
var $ = w['kb_' + new Date().getTime()] = {};
// local pointer back to document
$.d = d;
// our main function
$.f = (function () {
return {
init : function (findMe) {
var i, s;
// get all the SCRIPT tags on the page
s = $.d.getElementsByTagName('SCRIPT');
// start looping through them
for (i = 0; i < s.length; i = i + 1) {
// found it!
if (s[i].src.match(findMe)) {
// create a node
$.s = $.d.createElement('DIV');
$.s.innerHTML = 'Hello, world!';
// slide it in before the SCRIPT tag
s[i].parentNode.insertBefore($.s, s[i]);
// remove the SCRIPT tag
s[i].parentNode.removeChild(s[i]);
// stop immediately, so other instances can fire too
break;
}
}
}
};
}());
// we need to match as much of the script's name as possible
$.f.init(/widget\.js$/);
// in production, do something like this:
// /^https?:\/\/[^\/]*mydomain.com\/mypath\/myscript.js$/;
}(document, window));
// up next: passing configuration variables
// http://gist.github.com/313105
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment